华纳云香港服务器

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

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 主题添加了置顶文章功能,接下来只需要在后台编辑文章的时候,在公开度 – 公开中勾选“将文章置于首页顶端”或快速编辑勾选“置顶这篇文章”即可。

WordPress主题如何在首页和列表页添加置顶文章功能?-第1张-boke112百科(boke112.com)

列表页置顶文章效果图

温馨提示:

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

以上内容整理自@懿古今

本文地址:https://boke112.com/post/6059.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu