有人告诉我get_posts
是一个非常糟糕的函数new WP_query
绝对更好。
我的问题是get_posts
代码可以工作,但当我尝试将其转换为WP_query
, 它返回空白结果。请帮忙?:(我真的很想这样做,因为我怀疑index.php/category-9.php上的get\\u帖子干扰了category.php上的正常循环。)
Get\\u posts版本:
<?php if ( have_posts() ) : while ( (have_posts() ) ) : the_post(); ?>
<div class="postcontainer">
<h2><a href="<?php the_permalink();?>"><?php the_title(\'\'); ?></a></h2>
<?php
$args = array(
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'numberposts\' => 4,
\'post_status\' => null,
\'post_parent\' => $post->ID,
\'orderby\' => name,
\'order\' => ASC
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $post) {
setup_postdata($post); ?>
<a class="postpreview" href="<?php echo get_permalink($post->post_parent) ?>"><?php echo wp_get_attachment_image($post->ID, thumbnail) ?></a>
<?php };
}; ?>
<div class="clear"></div>
</div>
<?php endwhile; endif; wp_reset_query(); ?>
WP\\U查询版本:
<?php if ( have_posts() ) : while ( (have_posts() ) ) : the_post(); ?>
<div class="postcontainer">
<h2><a href="<?php the_permalink();?>"><?php the_title(\'\'); ?></a></h2>
<?php
$args = array(
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'numberposts\' => 4,
\'post_status\' => null,
\'post_parent\' => $post->ID,
\'orderby\' => name,
\'order\' => ASC
);
$attachments = new WP_Query($args);
while ($attachments->have_posts()) : ?>
<a class="postpreview" href="<?php echo get_permalink($post->post_parent) ?>"><?php echo wp_get_attachment_image($post->ID, thumbnail) ?></a>
<?php endwhile; wp_reset_postdata(); ?>
<div class="clear"></div>
</div>
<?php endwhile; endif; ?>
最合适的回答,由SO网友:cybmeta 整理而成
你忘了$query->the_post()
, 这与setup_postdata()
. 此外,您正在使用$post->ID
在回路内部,但$post
不是循环中的当前post对象。还有语法错误;例如,您通过thumnail
到wp_get_attachment_image()
而不是字符串"thumbnail"
, 并通过name
像orderby
参数而不是字符串"name"
, 或ASC
而不是"ASC"
:
<?php
//as you are inside a loop but I don\'t see $post variable in your code,
//I assume you want the current post in the loop as parent
$parent_id = get_the_ID();
$args = array(
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'posts_per_page\' => 4,
\'post_status\' => \'inherit\',
\'post_parent\' => $parent_id,
\'orderby\' => \'name\',
\'order\' => \'ASC\'
);
$attachments = new WP_Query($args);
while ($attachments->have_posts()) {
$attachments->the_post();
//I pass $parent_id to get_permalink() because you was trying
//to do that in your code but I\'m not sure if this is what you want
?>
<a class="postpreview" href="<?php echo get_permalink($parent_id); ?>"><?php echo wp_get_attachment_image(get_the_ID(), \'thumbnail\') ?></a>
<?php
}
wp_reset_postdata();
?>
不管怎样,
new WP_query
并不比
get_posts()
, 每一个都有它的好处,更好的取决于你想做什么。