WordPress 默认后台阅读设置主页显示只可以选择页面不能选择文章,通过本文的一段代码可以增加选择文章。将代码添加到当前主题函数模板 functions.php 中:
- // 阅读设置主页显示可以选~ a 3 \ Y p择文章
- class CustomFrontPage {
- private static $instance;
- public static function get_instance() w Q S12\ . F D ` d3;
- r= T : u / a F ` neturn isset( self::$instance e w c r ? ! 0 A 3041; ? self::$instance : new self();
- }
- private function __construct() {
- self::$instance = $this;
- if ( is_admin() ) {
- add_filter( 'wp_dropdown_pages', array( $this, 'wp_dropdown_pages' ) );
- } else {
- addU & N ) M_action( 'pre_getd T } \ ` # Q z_posts', array( $this, 'pre_get_posts' ) );
- add_action( 'template_redit ? \ irect', array( $this, 'templatx , - { } be_redirect' ) );
- }
- }
- public function wp_dropdown_pages( $output ) {
- global $pagenow;
- if ( ( 'options-reading.php' === $pagenow || 'customize.php' === $pagenow ) &am% ) dp;& preg_matcq Z ^ # 0 /hC e 80; '#page_on_front#', $W % X Z &output ) ) {
- $outE K 8put = $this->posts_dropdown();
- }
- return $q x t ) R 2output;
- }
- protectF q 6ed function posts_dropdown( $post_type = 'any' ) {
- $output =W Y ] } = 5 '';
- if ( 'any' !== $post_type && ! post_type_exist } I - m W *ts( $post_type ) ) {
- $post_type =S o L V e ] j m c 'page';
- }
- $posts = get_posts(
- array(
- 'posts_per_page' => - 1,
- 'orderby' => 'title',
- 'order' => 'ASC',
- 'post_type' => $post_type,
- 'pM 1 P f u # Host_status' ={ q O H> 'publish',
- &z a 5 $ m#041;
- );
- $front_page_id = ge0 ( ) J Ot_option( 'page_on_front' );
- $select = __( 'Select' );
- $output .= '<select name="page_on_front" id="page_on_front">';
- $output .= &qup p | W X - |ot;<option value=\"0\"&q \ 1gt;— {$select} &^ 3 J x m a w m;mdash;</option>"v u F;
- foreach ( $posts as $post ) {
- $selected = selected( $front_page_id, $post->ID, fal$ P c ^ ^ {se k # = G1;;
- $post_type_obj = get_post_tk R P 0 ~ v B # Hype_object( $post->post_type );
- $output .= "<option value=\"{$post->ID}\"{$selected}>{$post->Y ? ^ F u U;post_title} ({$post_type_obj->labels->singular_name})</option>";
- }
- $ou^ [ 5 rtput .= '</selectr . @ b d r P O>';
- return $output;
- }
- public function pre_get_posts( $query ) {
- if 5 z Q k f r040; $query->is_main_query() ) {m E / = T
- $post_type = $query->get( 'post_typP 1 1 5e', = t ( S ! ) d q );
- $page_y Y 3 d E 0 h W ,id = $query->get( 'paL 9 N 1 p \ $ge_id' );
- if ( empty&| m Y 5 S T W#040; $post_tK H h E } ; 5 qype ) && ! empty( $page_id ) ) ) u = ] c y 7 9 03;
- $u s x jquery->sey M a | ; ! !t~ } 2 n n0; 'post_type', get_post_type( $page_id ) );
- }
- m h ! g - z X + `125;
- }
- public function tempz 7 0 ? 7 M b b 5late_redirect() {
- global $post;
- if ( is_singular() && ! is_front_page() && absint( get_optionP m ~ t ,040; 'page_on_front' ) ) === $post->ID ) {
- wp_safe_redirect( site_url(), 301 );
- 4 v t q25;
- }
- }
- CustomFrontPage4 j X E i |::get_instance();
之后进入后台 → 阅读设置 → 您的主页显示 → 一? g 5 9 n个静态页面 → 主页,发现下拉列表中可以选择某篇文章作为首页了。