当我运行此代码时,它会输出特定类别中的所有帖子,每个帖子都在<li>
标记中。出于某种原因,最后一项还有我不想要的帖子缩略图。
我创建了一个自定义短代码来显示特定类别中的所有帖子:
function getPostbyCategory($atts) {
extract(shortcode_atts(array(
"slug" => 'tutorials'
), $atts));
global $post;
$args = array(
'category_name' => $slug,
'posts_per_page' => 2000,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
);
$buildOuput = "<ul>";
$posts_array = get_posts( $args );
foreach ( $posts_array as $post ) {
$buildOuput .= "<li><a href=".get_the_permalink($post->ID).">".get_the_title()."</a></li>";
}
$buildOuput .= "</ul>";
return $buildOuput;
wp_reset_postdata();
}
add_shortcode("specificcategoryposts","getPostbyCategory");
以下是帖子中的所有内容:
<div class="row">
<div class="two-thirds column">
<h2>Category</h2>
<p>Lorem Ipsum Dolor Sit Amet</p>
[specificcategoryposts slug="tutorials"]
</div>
<div class="one-third column ">
<img src="example.com/title-img.png" alt="Title Image" />
</div>
</div>
<div class="row">
<div class="two-thirds column">
<h2>Category</h2>
<p>Lorem Ipsum Dolor Sit Amet</p>
<ul>
<li><a href="#link1">postTitle1</a></li>
<li><a href="#link2">postTitle2</a></li>
</ul>
</div>
<div class="one-third column">
<img src="example.com/title-img.png" alt="Title Image" />
</div>
</div>
// Then it outputs this, outside of everything:
<div class="one-third column">
<img width="738" height="492" src="http://example.com/featured-image.png" class="hide-mobile wp-post-image" alt="iOS Development Swift Tutorial">
</div>
关于魔鬼在这里发生了什么的任何想法。
答案 0 :(得分:2)
不确定它将如何影响结果但返回语句在wp_reset_postdata之前。请参阅下面的更正。
对于函数引用,https://codex.wordpress.org/Function_Reference/wp_reset_postdata
function getPostbyCategory($atts) {
extract(shortcode_atts(array(
"slug" => 'tutorials'
), $atts));
global $post;
$args = array(
'category_name' => $slug,
'posts_per_page' => 2000,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
);
$buildOuput = "<ul>";
$posts_array = get_posts( $args );
foreach ( $posts_array as $post ) {
$buildOuput .= "<li><a href=".get_the_permalink($post->ID).">".get_the_title()."</a></li>";
}
$buildOuput .= "</ul>";
wp_reset_postdata(); // this line was previously beneath the return statement
return $buildOuput;
}
add_shortcode("specificcategoryposts","getPostbyCategory");