php - wordpress get_post_meta 不在循环中工作

标签 php wordpress

我正在尝试在按自定义字段“价格”排序的页面上获取帖子 我已经完成了排序,但现在我无法得到“价格”的回显值。 get_post_meta 不提供任何输出。这是代码:

$args=array(
'meta_key'=>'price',
'post_type' => 'page',
  'orderby'=>'meta_value_num',
  'post_status' => 'publish',
  'posts_per_page' => -1,
  'caller_get_posts'=> 1

);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
 $count=0;
  while ($count<4 && $my_query->have_posts()) : $my_query->the_post(); ?>

    <td><a href="<?php the_permalink(); ?>">
    <img alt="product" src="/product-images/image.jpg" height="100px" width="75px"/>
    <p><?php the_title(); ?></p>
    <?php echo get_post_meta($my_query->ID, 'price', true); ?>
    </a>
    </td>
    <?php
    $count++;
  endwhile;
}
wp_reset_query();  // Restore global post data stomped by the_post().
?>

最佳答案

您正在尝试使用 WP_Query 上的属性 ($ID) 而不是当前帖子的 ID。 get_post_meta 的第一个参数应该是帖子 ID,而不是 WP_Query 的属性。

如果这是模板中的某处,您可以这样做:

<?php
while ($my_query->have_posts()) {
    $my_query->the_post();

    // use the global $post object
    echo get_post_meta($post->ID, 'price', true);
}

如果它不在模板文件中或全局 $post 声明的地方,您可以使用 get_the_ID 代替:

<?php
while ($my_query->have_posts()) {
    $my_query->the_post();

    // use the global $post object
    echo get_post_meta(get_the_ID(), 'price', true);
}

关于php - wordpress get_post_meta 不在循环中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19860959/

相关文章:

php - 将两个表的结果合并为 JSON

php - 我想在用户使用 PHP 和 ImageManipulator 库上传个人资料图像时调整其大小

php - 如何通过ajax调用获取wp_usermeta中的meta_key及其meta_value(json格式)

wordpress - 没有作者的自定义帖子类型

php - 禁用 wp-admin 到 wp-login 规范重定向(wordpress)

file-upload - 为什么 php 中的文件上传错误代码未命中编号 '5'?

PHP CSS 选择器库?

javascript - 如何输出php?

php - WordPress 查询中排除/不等于多个值

php - WordPress:如何从 Json 中的 wordpress 函数获取响应?