WordPress主题如何在首页和列表页添加置顶文章功能?

秋天是金灿灿的丰收,秋天是沉甸甸的硕果,秋天是让人满载而归的欢笑和欣喜。

经常有站长问到如何添加置顶功能。今天懿古今就以WordPress 版本的 Blogs 主题为例添加首页和列表页的置顶功能,其他主题请参考折腾即可。

1、修改首页 index.php 文件

直接编辑 Blogs 主题的 index.php 文件,找到以下代码

<div id="post_list_box" class="border_gray">

在它下方添加以下代码:

<?php
$sticky = get_option( 'sticky_posts' );
query_posts( array('post__in' => $sticky,'showposts'=>3) );
?>
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" class="archive-list <?php $postds=$wp_query->current_post;if($postds % 2 ==0){echo "shuangshu";}?>">
<?php get_template_part( '/inc/content'); ?>
</article><!-- #post -->
<?php endwhile;endif; ?>

2、修改列表页 archive.php 文件

直接编辑 Blogs 主题的 archive.php 文件,找到以下代码

<div id="post_list_box" class="border_gray">

在它下方添加以下代码:

<?php
query_posts(array(
"category__in" => array(get_query_var("cat")),
"post__in" => get_option("sticky_posts"),
'showposts' => 3,
)
);
while(have_posts()) : the_post();
?>
<article id="post-<?php the_ID(); ?>" class="archive-list <?php $postds=$wp_query->current_post;if($postds % 2 ==0){echo "shuangshu";}?>">
<?php get_template_part( '/inc/content'); ?>
</article><!-- #post -->
<?php endwhile;wp_reset_query(); ?>

<?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$sticky = get_option( 'sticky_posts' );
$args = array(
'category__in' => array(get_query_var("cat")),
'post__not_in' => $sticky,
'paged' => $paged
);
query_posts( $args );
?>

3、修改 inc\content.php 文件

直接编辑 inc\content.php 文件,找到文章标题代码:

<?php the_title(); ?>

修改为

<?php if(is_sticky()){echo '【置顶】';}the_title(); ?>

至此,已经为 WordPress 版本的 Blogs 主题添加了置顶文章功能,接下来只需要在后台编辑文章的时候,在公开度 >> 公开中勾选“将文章置于首页顶端”或快速编辑勾选“置顶这篇文章”即可。

列表页置顶文章效果图

温馨提示:

  • 以上代码默认显示 3 篇置顶文章,想要显示更多只需要将 'showposts' => 3 中的 3 修改成其他数字即可。
  • 置顶样式默认只是在标题前方添加【置顶】字样而已,想要添加其他样式请自行编辑 inc\content.php 文件。
  • 如果不想折腾的话,直接点此下载“置顶修改文件(hc4b)”后上传覆盖即可。

内容整理自:懿古今 - https://www.yigujin.cn/1812.html

以上就是WordPress主题如何在首页和列表页添加置顶文章功能?。从绝望中寻找希望,不再做命运的玩偶,从此刻起命运掌握在我的手中。更多关于WordPress主题如何在首页和列表页添加置顶文章功能?请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
WordPress站点Gravatar头像前后台不显示的如何解决办法

WordPress做公司官网好吗?会不会显得档次很低?

WordPress主题需要支持https吗?WordPress站点如何如何实现https?

WordPress站点的页面/标签/分类URL地址如何添加.html?

WordPress站点更换了域名后数据库应该如何操作替换新旧域名?