簡體   English   中英

WordPress:如何使用query_posts返回元數據?

[英]WordPress: how to return meta with query_posts?

我正在使用admin-ajax.php進行AJAX請求,我根據檢查的復選框過濾帖子。 它工作得很好,雖然我很難找到一種方法來返回每個帖子的元細節。

我只是使用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按元數據過濾帖子,但我只想在帖子中顯示數據。

編輯:

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

基本上WP_Post對象(來自WP_Query的幾乎所有查詢結果中的posts數組)都使用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()調用,但是如果你要在你的代碼中進行任何其他的帖子查詢,那么它很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM