WordPress:如何使用query_posts返回元数据?

gra*_*ray 3 php ajax wordpress

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

我如何修改它以返回元数据?我知道我可以使用meta_query按元数据过滤帖子,但我只想在帖子中显示数据.

Nik*_*lov 10

编辑:

除了下面概述的解决方案,如果你使用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 );
}
Run Code Online (Sandbox Code Playgroud)

如果你创建一个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 );
}
Run Code Online (Sandbox Code Playgroud)

或者挂钩到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;
}
Run Code Online (Sandbox Code Playgroud)

然后你会改变你的

$posts=query_posts( $args);
Run Code Online (Sandbox Code Playgroud)

对此:

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

$posts = query_posts( $args );

remove_filter( 'the_posts', 'my_the_posts_filter', 10 );
Run Code Online (Sandbox Code Playgroud)

考虑到这会发生在AJAX请求中,你可以在技术上摆脱这个remove_filter()调用,但是如果你要在你的代码中进行任何其他的帖子查询,那么它很好.

  • 完美的答案,我结束了使用第一个解决方案,但第二个也很棒,因为我不知道这种方法。谢谢你,你节省了我几个小时 (2认同)