WordPress 主页显示设置增加文章选择

WordPress评论389阅读模式

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\">&mdash; {$select} &mdash;</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();

之后进入后台 → 阅读设置 → 您的主页显示 → 一个静态页面 → 主页,发现下拉列表中可以选择某篇文章作为首页了。

WordPress 主页显示设置增加文章选择

 

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖动滑块以完成验证