2013-10-28 66 views
2

我正在使用admin-ajax.php做一個AJAX請求,據此我過濾基於哪個複選框被選中的帖子。雖然我很努力地找到一種方法來返回每篇文章的元數據細節,但它工作得很好。WordPress:如何用query_posts返回meta?

我只是用query_posts下面把我的數據:

function ajax_get_latest_posts($tax){ 

    $args= array(
     'post_type'=>'course', 

    'tax_query' => array(
     array(
     'taxonomy' => 'subject', 
     'field' => 'slug', 
     'terms' => $tax 
    ) 
    ) 

); 

$posts=query_posts($args); 


return $posts; 
} 

我將如何修改這個也返回元數據?我知道我可以使用meta_query過濾元數據的帖子,但我只想在我的帖子中顯示數據。

+1

http://codex.wordpress.org/Class_Reference/WP_Query去那裏尋找'meta_query' – codepixlabs

回答

7

編輯:

除了解決方案概述波紋管,如果你使用WordPress> = 3.5(因爲你應該:)),你可以簡單地使用的WP_Post對象的魔術方法。

基本上,WP_Post對象(這是來自WP_Query的幾乎每個查詢結果的帖子數組由什麼組成)是使用PHP的__get()__isset()魔術方法。這些方法允許您使用對象本身未定義的對象的屬性。

下面是一個例子。

foreach ($posts as $key => $post) { 
    // This: 
    echo $post->key1; 
    // is the same as this: 
    echo get_post_meta($post->ID, 'key1', true); 
} 

如果你犯了一個print_r($post)var_dump($post),你將不會看到$post對象的「KEY1」屬性。但功能__get()允許您訪問該屬性。

============================================== =============

在我看來,你有兩個常規選項 - 循環訪問並獲取所需的數據,如下所示(此代碼將在$posts = query_posts($args);之後):

foreach ($posts as $key => $post) { 
    $posts[ $key ]->key1 = get_post_meta($post->ID, 'key1', true); 
    $posts[ $key ]->key2 = get_post_meta($post->ID, 'key2', true); 
} 

或鉤到the_posts過濾器鉤和做同樣的事情有(更多的工作,但如果你有需要的數據添加到每個崗位多種功能 - 這可能是更容易)。此代碼會去你的functions.php或插件的文件(如果你正在做一個插件):

function my_the_posts_filter($posts) { 
    foreach ($posts as $key => $post) { 
     $posts[ $key ]->key1 = get_post_meta($post->ID, 'key1', true); 
     $posts[ $key ]->key2 = get_post_meta($post->ID, 'key2', true); 
    } 

    return $posts; 
} 

然後你將你的

$posts=query_posts($args); 

行改成這樣:

add_filter('the_posts', 'my_the_posts_filter', 10); 

$posts = query_posts($args); 

remove_filter('the_posts', 'my_the_posts_filter', 10); 

考慮到這會發生在AJAX請求中,您可以在技術上擺脫remove_filter()調用,但是如果您打算進行其他任何後續查詢在你的代碼中。

+1

完美的答案,我結束了第一個解決方案,但第二個也很棒,因爲我沒有意識到這個方法。謝謝你,我節省了時間 – gray

+1

我更新了我的答案 - 我完全忘記了WP_Post對象的魔術方法 - 它們更容易使用:)。基本上,您可以只訪問元鍵作爲對象的屬性。請隨時查看這裏的代碼 - http://core.trac.wordpress.org/browser/tags/3.7/src/wp-includes/post。php#L648,看看你可以訪問哪些東西(比如'$ post-> page_template';)) –

+1

太好了,謝謝!還沒有使用WP_Post,它看起來更簡單一些。感謝修改,祝你好運 – gray