[英]Show last 5 posts from specific category (Wordpress)
I'm trying to show the last 5 posts from a specific category, which will be linked to a function so I can insert the shortcode in a Wordpress page. 我正在尝试显示特定类别的最后5个帖子,这些帖子将链接到一个函数,以便可以在Wordpress页面中插入简码。 The code I have is as below, it does everything I need (although I want to add featured image too) except it does not show posts from a specific category. 我拥有的代码如下,它可以执行我需要的所有操作(尽管我也想添加特色图片),但是它不显示特定类别的帖子。
I've tried numerous things, but cannot find a working fix. 我已经尝试了很多事情,但是找不到有效的解决方案。
function Last5posts()
{
$args = array( "showposts" => 5, "category" => 3 );
$content = "";
query_posts($args);
if ( have_posts() ) :
while ( have_posts() ) :
the_post();
$link = get_permalink();
$title = get_the_title();
$date = get_the_date();
$content .= "<div class='latest-posts'>";
$content .= "<h3><a href='$link' target='_top'>$title / $date</a </h3>\n";
$content .= "<p class='excerpt'>" . get_the_excerpt() . "</p>";
$content .= "</div>";
endwhile;
wp_reset_query();
endif;
return $content;
}
add_shortcode('Last5Posts', 'Last5posts' );
I have tried replacing lines 3 and 4 with the code below, but it throws an error "syntax error, unexpected '}' on line 31". 我尝试用下面的代码替换第3行和第4行,但是它引发错误“语法错误,第31行出现意外的'}'。
$catquery = new WP_Query( 'cat=3&posts_per_page=10' );
while($catquery->have_posts()) : $catquery->the_post();
Any help would be greatly appreciated. 任何帮助将不胜感激。
you can use code just like below 您可以像下面一样使用代码
query_posts( 'cat=3&posts_per_page=5' );
using this wordpress by default will use last 5 post after this code... 默认情况下使用此wordpress将在此代码后使用最后5个帖子...
Use this 用这个
$catnames[1] denotes which category u want to use related to that post. $ catnames [1]表示您要使用与该帖子相关的类别。
<?php $catnames = get_the_category();
$postcatid=$catnames[1]->term_id;
$catquery = new WP_Query( 'cat='.$postcatid.'&posts_per_page=4' );
while($catquery->have_posts()) : $catquery->the_post();
?>
<ul>
<li><h3><a href="<?php the_permalink() ;?>" rel="bookmark"><?php the_title(); ?></a> </h3>
</li>
</ul>
<?php endwhile;
?>
Check this out: query posts parameters ; 检查一下: 查询发布参数 ; you should definitely using "cat" instead of category. 您绝对应该使用“ cat”而不是类别。 Also, are you ending your "while" with an "endwhile;"? 另外,您是否以“ endwhile;”结束“ while”? What does your complete code now look like? 您的完整代码现在看起来像什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.