function related_posts_shortcode( $atts, $content = null ) {
//extract the shortcode atts and set default
extract( shortcode_atts( array(
\'cat\' => \'\',
\'limit\' => 4
), $atts ) );
//store the current post ID so we don\'t display it as featured
$post_ID = get_the_ID();
//set up our args for the query
$args = array(
\'cat\' => $cat,
\'posts_per_page\' => $limit
);
$html = \'\';
$i = 0;
//query for our posts
$posts = new WP_Query( $args );
//if we have posts, loop them
if( $posts->have_posts() ): while( $posts->have_posts() ): $posts->the_post();
//check to make sure not the same post as main post
if ( $post_ID != get_the_ID() )
//if post has thumbnail display it with link to post
if ( has_post_thumbnail( get_the_ID() ) ) {
$html .= \'<a href="\' . get_the_permalink(); . \'">\';
$html .= get_the_post_thumbnail( get_the_ID() );
$html .= \'</a>\';
}
$html .= \'<a href="\' . get_the_permalink(); . \'">\';
$html .= \'<h2>\' . get_the_title() . \'</h2>\'; //set link on title and display it
$html .= \'</a>\';
++$i;
}
//if $i == 2 ( $limit default - 2 ) we have three posts so break, change for more posts, i just went off of your image example
if ( $i == $limit - 2 ) break;
endwhile;
endif;
//even though WP_Query doesn\'t effect the main loop, reset it as precaution
wp_reset_query();
//return generated html for recent posts
return $html;
}
add_shortcode( \'related_posts\', \'related_posts_shortcode\' );
将以下代码添加到函数中。php文件,然后在帖子中可以执行以下操作:
[related_posts cat="6" limit="4"/]
cat是你想要的帖子类别,limit是你想要的相关帖子数量(+1):加1的原因是因为你不想返回当前帖子,所以我们会多留一个,以防我们在循环中碰到当前帖子。你也可以在任何帖子中使用这个。如果要在模板中使用它,只需执行以下操作:
<?php do_shortcode("[related_posts cat=\'6\' limit=\'4\'/]"); ?>
希望这对您有所帮助!