Wordpress 之 Rewrite Rules

-----------------------------------------------------------------

场景描述:

       自定义wp主题中,添加了个关于页面(about.php) 。

目的:

  顺利访问 http://<domain>/about.php 

-----------------------------------------------------------------

解决方案:在主题的functions.php文件中, 自定义重写规则 rewrite_rules

-----------------------------------------------------------------

Step 1.  添加 generate_rewrite_rules

if ( ! function_exists( 'testthemes_rewrite_rules' ) ) :
	/**
	 * @param WP_Rewrite $wp_rewrite
	 */
	function testthemes_rewrite_rules( $wp_rewrite ) {
		$testthemes_rules = [
			'about(.*)$' => 'index.php?my_custom_page=about',
		];

		$wp_rewrite->rules = $testthemes_rules + $wp_rewrite->rules;
	}
endif; // testthemes_rewrite_rules

add_action( 'generate_rewrite_rules', 'testthemes_rewrite_rules' );

  

说明:
pattern=>url格式: 'about(.*)$' => 'index.php?my_custom_page=about'

-----------------------------------------------------------------

Step 2.  添加 query_vars

if ( ! function_exists( 'testthemes_add_query_vars' ) ) :
	/**
	 * @param array $public_query_vars
	 * @return array
	 */
	function testthemes_add_query_vars($public_query_vars) {
		$public_query_vars[] = 'my_custom_page';
		return $public_query_vars;
	}
endif;
add_action( 'query_vars', 'testthemes_add_query_vars' );

  

 

-----------------------------------------------------------------

Step3.   添加 template_redirect 

if ( ! function_exists( 'testthemes_template_redirect' ) ) :
	/**
	 * @void
	 */
	function testthemes_template_redirect() {
		global $wp;
		/**@var WP_Query $wp_query*/
		global $wp_query;
		/**@var WP_Rewrite $wp_rewrite*/
		global $wp_rewrite;

		//查询my_custom_page变量
		$my_custom_page =  $wp_query->query_vars['my_custom_page'];
		switch ($my_custom_page) {
			case 'about':
				include(TEMPLATEPATH.'/about.php');
				die();
		}
	}
endif;
add_action( 'template_redirect', 'testthemes_template_redirect' );

  

-----------------------------------------------------------------

Step4.   添加 load-themes.php

if ( ! function_exists('testthemes_flush_rewrite_rules')):
	/**
	 * @void
	 */
	function testthemes_flush_rewrite_rules(){
		/**@var string $pagenow*/
		global $pagenow;
		/**@var WP_Rewrite $wp_rewrite*/
		global $wp_rewrite;

		if( 'theme.php' == $pagenow && isset( $_GET['activated'] )) {
			$wp_rewrite->flush_rules();
		}
	}
endif;
add_action( 'load-themes.php', 'testthemes_flush_rewrite_rules' );

  

-----------------------------------------------------------------

Step5.   重新激活主题

 

END

 

posted @ 2017-07-13 11:31  L狗哥  阅读(840)  评论(0编辑  收藏  举报