当前位置:首页>网站建设>WordPress 主页显示设置增加文章选择

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

释放双眼,带上耳机,听听看~!

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 主页显示设置增加文章选择
欢迎访问秀主题博客,分享简单实用WP教程
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
网站建设

WordPress调用文章作者名称代码

2025-2-15 15:04:48

网站建设

非插件扩展wordpress分类,增加分类关键词自定义字段

2025-2-20 13:38:21

温馨提示:

1.本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:971318156@qq.com,我们将第一时间处理!

2.资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。

3.所有资源仅限于参考和学习,版权归原作者所有,更多请阅读网站声明

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索