如何在WordPress网站显示最新置顶文章

wufei123 发布于 2024-08-24 阅读(13)

置顶文章是WordPress中一项很受人欢迎的功能置顶文章是博客中必将有特点的文章,当你把一篇文章标记为置顶文章时,这篇文章将会在最新文章的顶部显示,但是前提条件是网站主题允许设置置顶文章我们将通过这篇文章为大家介绍如何在WordPress网站中显示最新置顶文章。

提示:该教程属于中级教程需要有一定的HTML/CSS基础和WordPress主题的相关知识首先需要我们做的是复制并黏贴下述代码到你的WordPress主题的functions.php文件或一个site-specific plugin中。

function wpb_latest_sticky {/* Get all sticky posts */$sticky = get_option( sticky_posts );/* Sort the stickies with the newest ones at the top.

* Remove this if you want to display oldest posts first*/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, caller_get_posts => 1 ) );

// The Loopif ( $the_query->have_posts ) {$return .= ;while ( $the_query->have_posts ) {$the_query->the_post;

$return .= ID). " title=" . get_the_title . "> . get_the_title . ;

}$return .= ;} else {// no posts found}/* Restore original Post Data */wp_reset_postdata;return $return;

}add_shortcode(latest_stickies, wpb_latest_sticky);上面的代码已经封装成一个函数并创建了一个短代码其功能是查询Wordpress数据库检索最新的五篇置顶文章。

然后以列表的形式显示每片置顶文章的题目和链接现在你可以通过在任意文章、页面甚至是一个text widget中添加短代码:[latest_stickies]来显示最新的置顶文章如果你想要在一个文本组件中使用短代码,你还需要在主题的functions.php或site-specific plugin中另外添加如下一行代码:。

add_filter(widget_text, do_shortcode);这段代码可以用于功能滑块,或任意你想要在你网页上显示的其他优先项目该代码大多面向具有自定义主页或杂志风格的网站这篇文章就写到这里,希望对您有所帮助。

亲爱的读者们,感谢您花时间阅读本文。如果您对本文有任何疑问或建议,请随时联系我。我非常乐意与您交流。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。