跳到主要内容

WordPress具有此非常酷的功能,称为粘帖。将粘性帖子视为博客的特色帖子。当您将帖子标记为粘性时,它会显示在新帖子上方,但前提是您的主题允许。在本教程中,我们将向您展示如何在WordPress中显示最新的即时贴。

如何在wordpress中显示最新的即时贴
如何在wordpress中显示最新的即时贴

注意:这是中级教程,需要基本的HTML / CSS知识+ WordPress主题知识。

您需要做的第一件事是将该代码段复制并粘贴到主题的functions.php文件或特定于站点的插件中。

function wpb_latest_sticky() { 

/* Get all sticky posts */
$sticky = get_option( 'sticky_posts' );

/* Sort the stickies with the newest ones at the top */
rsort( $sticky );

/* Get the 5 newest stickies (change 5 for a different number) */
$sticky = array_slice( $sticky, 0, 5 );

/* Query sticky posts */
$the_query = new WP_Query( array( 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ) );
// The Loop
if ( $the_query->have_posts() ) {
	$return .= '<ul>';
	while ( $the_query->have_posts() ) {
		$the_query->the_post();
		$return .= '<li><a href="' .get_permalink(). '" title="'  . get_the_title() . '">' . get_the_title() . '</a><br />' . get_the_excerpt(). '</li>';
		
	}
	$return .= '</ul>';
	
} else {
	// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

return $return; 

} 
add_shortcode('latest_stickies', 'wpb_latest_sticky');

上面的代码查询WordPress数据库以检索5个最新的即时贴。然后,它以列表格式显示每个即时贴的标题和链接。我们将所有内容包装在一个函数中,并创建了一个简码。

现在要显示最新的粘性帖子,您可以在任何WordPress帖子,页面甚至文本小部件中使用短代码[latest_stickies]。

如果您想在文本小部件内使用简码,则需要在主题的functions.php或特定于站点的插件中添加此额外的代码行。

add_filter('widget_text', 'do_shortcode');

此代码段和功能可以很好地用于特色滑块或您要在网站上显示的任何其他高级功能。此代码段主要是针对具有自定义首页或杂志风格的WordPress网站

回到顶部