可锐资源网

技术资源分享平台,提供编程学习、网站建设、脚本开发教程

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

置顶文章是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 Loop

if ( $the_query->have_posts ) {

$return .= '<ul>';

while ( $the_query->have_posts ) {

$the_query->the_post;

$return .= '<li><a href="' .get_permalink($post->ID). '" title="' . get_the_title . '">' . get_the_title . '</a></li>';

}

$return .= '</ul>';

} 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');

这段代码可以用于功能滑块,或任意你想要在你网页上显示的其他优先项目。该代码大多面向具有自定义主页或杂志风格的网站。

这篇文章就写到这里,希望对您有所帮助。

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言