2015-01-11 94 views
0

我有一個函數在Wordpress中獲取字段並返回一個字符串。該函數在當前帖子上調用時工作正常,但現在我需要讓該函數在當前帖子之外運行,並從其他帖子中獲取數據。我正在嘗試:如何在wordpress中的特定帖子上運行功能?

$posts = get_posts(array(
    'numberposts' => -1, 
    'post_type' => 'post' 
)); 

if($posts) { 
    foreach($posts as $post) { 
     $postid = $post->ID; 
     $datafrompost[] = custom_func($postid); 
    } 
    echo print_r($datafrompost); 
} 

如何獲取運行其他帖子的功能?

下面是何許功能將獲取的例子:

//[inactivesubjects] 
function inactivesubjects_func($atts){ 
$inactivesubjects = get_field('inactive_subjects'); 
return $inactivesubjects; 
} 
add_shortcode('inactivesubjects', 'inactivesubjects_func'); 

此功能工作正常,當它在目前的職位是運行獲取inactive_subjects內容。

//////////////////////////// UPDATE ///////////////// //////////

所以以下流浪漢的建議,我會被添加到這個功能:

//[inactivesubjects] 
function inactivesubjects_func($anact){ 
$inactivesubjects = get_field('inactive_subjects', $anact); 
return $inactivesubjects; 
} 
add_shortcode('inactivesubjects', 'inactivesubjects_func'); 

這將呼叫

$posts = get_posts(array(
    'numberposts' => -1, 
    'post_type' => 'post' 
)); 

if($posts) { 
    foreach($posts as $post) { 
     $datafrompost[] = inactivesubjects_func($anact); 
    } 
    echo print_r($datafrompost); 
} 

但它不是」指定一個職位?

//////////////////// UPDATE 2 //////////////////////

真正混淆了我,這是將工作

$posts = get_posts(array(
    'numberposts' => -1, 
    'post_type' => 'post' 
)); 

if($posts) { 
    foreach($posts as $post) { 

    $string = get_field('inactive_subjects', $post->ID); 
    } 
    echo print_r($string); 
} 

爲什麼不能我在foreach使用inactivesubjects_func()? (注意,其中的inactivesubjects_func()就是一個例子,我試圖在其他帖子上運行的實際功能比較大)

+1

你的'if語句'應該說'if($ posts)'。你忘了最後一個。 – RST

+0

對不起,這是我輸入到stackoverflow。我使用的代碼確實有$ posts – user1721230

+0

我很確定custom_func($ postid)是錯誤的。我希望函數能夠在所有帖子上運行,並從所有帖子中返回函數返回的字符串。 – user1721230

回答

1

你不是在跟着我說的 - 你改變的比我說的要多也許評論太短讓我解釋清楚)。根據你的第一次編輯,這應該工作。

$posts = get_posts(array(
    'numberposts' => -1, 
    'post_type' => 'post' 
)); 

if($posts) { 
    foreach($posts as $post) { 
     $datafrompost[] = inactivesubjects_func($post->ID); 
    } 
    echo print_r($datafrompost); 
} 

function inactivesubjects_func($anact){ 
    $inactivesubjects = get_field('inactive_subjects', $anact); 
    return $inactivesubjects; 
} 

,如果你想使用inactivesubjects_func作爲短碼,因爲WordPress的簡碼傳遞參數的方式,但這是另外一個問題你有問題。

+0

Cor的人。感謝您結束那場噩夢! – user1721230

+0

無後顧之憂;很高興我們到了那裏。 – Hobo

+0

而短代碼仍然有效,唷 – user1721230

相關問題