【问题标题】:WordPress: how to return meta with query_posts?WordPress:如何使用 query_posts 返回元数据?
【发布时间】:2013-11-07 13:59:03
【问题描述】:

我正在使用 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 按元数据过滤帖子,但我只想在我的帖子中显示数据。

【问题讨论】:

标签: php ajax wordpress


【解决方案1】:

编辑:

除了下面列出的解决方案之外,如果您使用的是 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() 调用,但最好有它以防万一您要在代码中进行任何其他帖子查询.

【讨论】:

  • 完美答案,我结束了使用第一个解决方案,但第二个也很棒,因为我不知道这种方法。谢谢,你为我节省了几个小时
  • 我更新了我的答案——我完全忘记了 WP_Post 对象的神奇方法——它们更容易使用:)。基本上,您可以将元键作为对象的属性来访问。随意查看这里的代码 - core.trac.wordpress.org/browser/tags/3.7/src/wp-includes/… 并查看您可以访问的其他内容(例如 $post->page_template ;))
  • 太好了,谢谢!还没有用过 WP_Post,它看起来确实有点简单。感谢您的修改,祝 Paiyak 好运
猜你喜欢
  • 2014-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多