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