在WordPress中,要在分类档案页面显示该分类的置顶文章,可以通过修改分类档案模板文件来实现。以下是一个简单的代码示例,废话不多说,直接将以下代码粘贴到functions.php中:

添加代码到functions.php

class StickyInCategory {
  private static $instance;
  protected $categories;
  public static function get_instance() {
    if ( null == self::$instance ) {
      self::$instance = new StickyInCategory();
    }
    return self::$instance;
  }

  private function __construct() {
    $this->categories = array();
    // Filter retrieved posts
    add_filter(  'the_posts', array( $this, 'prepend_sticky_posts' ), 10, 2 ); 
    // Set the 'sticky' class
    add_filter( 'post_class', array( $this, 'set_sticky_post_class' ), 10, 3 );
  }
 
  public function prepend_sticky_posts( $posts, $query ) {
    if ( !is_admin() && is_main_query() ) {  

      if ( empty( $this->categories ) ) {
        $this->categories = apply_filters( 'sia_sticky_categories', $this->categories );
      }

      if ( array_key_exists( 'category_name', $query->query_vars ) ) {
        $category_matched = false;
        if ( empty( $this->categories ) ) {
          
          $category_matched = true;
        }
        else {
          
          $category_matched = in_array( $query->query_vars['category_name'], $this->categories );
        }
 
        if ( $category_matched ) {
          // Copied from the bottom of WP_Query::get_posts() in wp-includes/class-wp-query.php
          $sticky_posts = get_option( 'sticky_posts' );
          $num_posts = count( $posts );
          $sticky_offset = 0;
   
          for ( $i = 0; $i < $num_posts; $i++ ) {
            if ( in_array( $posts[ $i ]->ID, $sticky_posts ) ) {
              $sticky_post = $posts[ $i ];
              // Remove sticky from current position
              array_splice( $posts, $i, 1 );
              // Move to front, after other stickies
              array_splice( $posts, $sticky_offset, 0, array( $sticky_post ) );
              // Increment the sticky offset. The next sticky will be placed at this offset.
              $sticky_offset++;
              // Remove post from sticky posts array
              $offset = array_search( $sticky_post->ID, $sticky_posts );
              unset( $sticky_posts[ $offset ] );
            }
          }
        }
      }
    }
    return $posts;
  }

  public function set_sticky_post_class( $classes, $class, $post_ID ) {
    
    // TODO: Consider whether to reference $this->categories.
    if ( is_archive() && is_sticky( $post_ID ) ) {
      $classes[] = 'sticky';
    }
    return $classes;
  }
}
 
add_action( 'after_setup_theme', array( 'StickyInCategory', 'get_instance' ) );

前端效果测试

前端文章排序中置顶类型文章按照后台上传的时间先后顺序排列;置顶文章优先排在非置顶文章前面。

前端置顶文章显示效果

关于如何实现文章标题前添加置顶图标可以查看往期文章。请点击👉 文章标题前添加置顶图标

* 文章内容很有用,那就5星好评吧!😘

0 / 5 好评 5

Your page rank:

发表回复

Please Login to Comment
数字人
微信

扫码了解更多服务

qr

1对1专家沟通

小程序

funion_xcx