WordPress 默认后台阅读设置主页显示只可以选择页面不能选择文章,通过本文的一段代码可以增加选择文章。
将代码添加到当前主题函数模板functions.php中:
// 阅读设置主页显示可以选择文章 class CustomFrontPage { private static $instance; public static function get_instance() { return isset( self::$instance ) ? self::$instance : new self(); } private function __construct() { self::$instance = $this; if ( is_admin() ) { add_filter( \'wp_dropdown_pages\', array( $this, \'wp_dropdown_pages\' ) ); } else { add_action( \'pre_get_posts\', array( $this, \'pre_get_posts\' ) ); add_action( \'template_redirect\', array( $this, \'template_redirect\' ) ); } } public function wp_dropdown_pages( $output ) { global $pagenow; if ( ( \'options-reading.php\' === $pagenow || \'customize.php\' === $pagenow ) && preg_match( \'#page_on_front#\', $output ) ) { $output = $this->posts_dropdown(); } return $output; } protected function posts_dropdown( $post_type = \'any\' ) { $output = \'\'; if ( \'any\' !== $post_type && ! post_type_exists( $post_type ) ) { $post_type = \'page\'; } $posts = get_posts( array( \'posts_per_page\' => - 1, \'orderby\' => \'title\', \'order\' => \'ASC\', \'post_type\' => $post_type, \'post_status\' => \'publish\', ) ); $front_page_id = get_option( \'page_on_front\' ); $select = __( \'Select\' ); $output .= \'<select name=\"page_on_front\" id=\"page_on_front\">\'; $output .= \"<option value=\\\"0\\\">— {$select} —</option>\"; foreach ( $posts as $post ) { $selected = selected( $front_page_id, $post->ID, false ); $post_type_obj = get_post_type_object( $post->post_type ); $output .= \"<option value=\\\"{$post->ID}\\\"{$selected}>{$post->post_title} ({$post_type_obj->labels->singular_name})</option>\"; } $output .= \'</select>\'; return $output; } public function pre_get_posts( $query ) { if ( $query->is_main_query() ) { $post_type = $query->get( \'post_type\' ); $page_id = $query->get( \'page_id\' ); if ( empty( $post_type ) && ! empty( $page_id ) ) { $query->set( \'post_type\', get_post_type( $page_id ) ); } } } public function template_redirect() { global $post; if ( is_singular() && ! is_front_page() && absint( get_option( \'page_on_front\' ) ) === $post->ID ) { wp_safe_redirect( site_url(), 301 ); } } } CustomFrontPage::get_instance();
之后进入后台 → 阅读设置 → 您的主页显示 → 一个静态页面 → 主页,发现下拉列表中可以选择某篇文章作为首页了。
源代码取自
暂无评论内容