编辑
You have indicated that you wish to reuse this code, so it is better used within a function so that it can be called whenever you desire. I\'ve made changes to my answer to reflect this below.
您可以使用下面的代码生成一个帖子列表(在您的情况下是2个随机帖子)以及一个标题。输出的格式由问题中的图像指示。此代码可以在主题中的任何位置使用-
my_post_list();
完成以下所有工作的函数应放置在
functions.php.
如果愿意,可以向函数传递不同的列表标题,以及不同的$args
大堆这允许您自定义随机帖子的范围,针对特定的类别或标签,只搜索特定的日期范围,或者只查找设置了一些自定义数据值的帖子,例如,可能性是无限的。查看Class Reference for WP_Query
有关如何使用这些参数的更多信息。
/**
* Output a list of posts under a heading
*
* @param string $title The title to output in the list heading
* @param array $args The arguments for getting the required posts
*/
function my_post_list($title = \'You may also like to read:\', $args = array()){
$defaults = array( // Set some defaults for querying the Posts
\'ignore_sticky_posts\' => true,
\'posts_per_page\' => 2,
\'post_status\' => \'publish\',
\'orderby\' => \'rand\'
);
$args = wp_parse_args($args, $defaults); // Parse any arguments passed to this function with the defaults to create a final \'$args\' array
$random = new WP_Query($args); // Query the Posts
if($random->have_posts()) : // Check to make sure some random Posts were returned
echo \'<h4>\' . $title . \'</h4>\';
echo \'<ul>\';
while($random->have_posts()) : $random->the_post(); // Create a new custom Loop, and for each Post set up the postdata
printf(\'<li id="random-post-%1$s">\', get_the_ID());
printf(
\'<a href="%1$s" title="%2$s">%3$s</a>\',
get_permalink(get_the_ID()),
the_title_attribute(\'before=Check out \\\'&after=\\\'&echo=0\'),
get_the_title()
);
echo \'</li>\';
endwhile;
wp_reset_postdata(); // Reset the postdata so that the rest of your Loop will work correctly
echo \'</ul>\';
endif;
}