2012-09-08 54 views
1

爲什麼如果我從functions.php中調用自定義函數,它不起作用?WordPress的:使用functions.php和foreach循環

我的自定義函數:

function get_cat_slug($ID) { 
    $post_id = (int) $ID; 
    $category = &get_category($post_id); 
    echo $category->slug; 
} 

環槽的所有帖子,這樣的:

$args = array(
'numberposts' => -1 
); 
$posts = get_posts($args); 
foreach ($posts as $post){ 
    // and withing this lopp I would like to get a category slug 
    // so I am calling my custom function, also included in functions.php 
    get_cat_slug($post->ID); 

} 

但是,get_cat_slug($post->ID)總是返回null。爲什麼?我錯過了什麼? 任何建議非常感謝。

回答

2

應該肯定不會get_category前一個符號,它實際上需要a Category ID and not a post ID

get_the_category返回類型的數組(因爲職位可以有多個),並且還做不需要指定(int)。如果你只是想呼應第一貓的蛞蝓(假設單一分類)嘗試:

function get_cat_slug($post_id) { 
    $cat_id = get_the_category($post_id); 
    $category = get_category($cat_id[0]); 
    echo $category->slug; 
} 

繼WordPress的功能的款式,不過,如果你與get_...,它應該命名你的函數return $category->slug而非echo它意味着你必須在模板循環中使用echo get_cat_slug($post->ID);

您的循環取決於WP_Query,它屬於模板文件而不屬於functions.php。哪個模板文件取決於您的循環的用途以及要顯示的目的。 index.php是主後循環的合理選擇,但是archive.php,single.php或任何預先存在的特定於主題的模板也可能有意義,就像您創建的任何自定義非標準模板一樣。

+0

更改後,我的函數仍然返回null。如何檢查函數是否正在調用? – Iladarsda

+0

你在哪裏運行你的循環?你應該檢查你是否確實在get_cat_slug調用中傳遞了一個有效的職位ID。 'echo $ post-> ID',然後調用get_cat_slug函數。 – crowjonah

+0

如果你看到空輸出,函數被調用 – crowjonah

1

可能是你的施法應

$post_id = intval($ID); 

ref

您是否嘗試過記錄的每一步?所以,你可以準確地看到它出錯