我在页面上使用WP_Query
来检索具有自定义帖子类型和特定元值的某些记录。
请求和计数看起来是正确的,但是当我实际循环记录时,我获得了具有自定义帖子类型的所有记录,就好像没有应用元值(即看起来我得到的是什么)我会在默认循环中看到 - 而不是我使用自定义查询得到的内容。
这是查询设置(带有一些调试信息)......
<?php
$args= array(
'post_type' => 'videos',
'posts_per_page' => 4,
'offset' => 0,
'meta_key' => 'custom_field',
'meta_value' => '1'
);
$videoQuery = new WP_Query($args);
echo $videoQuery->request;
echo '-->' . $videoQuery->found_posts;
?>
来自->request
的查询符合预期:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_postmeta
ON ( wp_posts.ID = wp_postmeta.post_id )
WHERE 1=1
AND ( ( wp_postmeta.meta_key = 'custom_field' AND wp_postmeta.meta_value = '1' ) )
AND wp_posts.post_type = 'videos'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 4
发现的帖子也是预期的1:
- →1
如果我运行查询,我会得到我期望看到的ID。
但是当我循环结果时,我得到了大量的记录输出(它们看起来像我在默认循环中找到的记录而不是我的WP_Query的记录):
<?php if ($videoQuery->have_posts()) : ?>
<div>
<?php while ($videoQuery->have_posts()) : $videoQuery->the_post(); ?>
<article>
<?php the_field('custom_thing_video'); ?>
<?php the_field('custom_thing_name'); ?>
<div class="tax">
<?php echo get_the_term_list( $post->ID, 'video' ); ?>
</div>
</article>
<?php endwhile; ?>
</div>
<?php endif; ?>
我错过了什么会在循环中给我正确的信息?
答案 0 :(得分:0)
嗯,这很有效 - 但似乎违背了这些建议......我很高兴接受另一个与WP_Query
有关的答案。
参数相同......但我在帖子中使用get_posts
然后foreach
。
<?php
$args= array(
'post_type' => 'videos',
'posts_per_page' => 4,
'offset' => 0,
'meta_key' => 'custom_field',
'meta_value' => '1'
);
$videos = get_posts($args);
?>
<?php if ($videos) : ?>
<div>
<?php foreach($videos as $video) {
$videoId = $video->ID ?>
<article>
<?php echo get_field('custom_thing_video', $videoId); ?>
<?php echo get_field('custom_thing_name', $videoId); ?>
<div class="tax">
<?php echo get_the_term_list($videoId, 'video'); ?>
</div>
</article>
<?php } ?>
</div>
<?php endif; ?>