在WordPress中为重写路径的页面指定关键字和描述(rewrite_rules)

导语:叶子在为一个客户做开发的时候,它的部分页面的路径做了重写,他又希望对这些动态生成的页面能够手动配置标题、关键字和描述。叶子想了一个办法,先让标题、关键字和描述存在一个自定义字段里面,当访问重写路径的页面时,动态的读出这些数据。

重写路径

重新路径怎么实现,叶子在这里就不详细说了,这里点一下四个关键点的add_action。

启用主题的时候,刷新规则

add_action( 'load-themes.php', 'yours_flush_rewrite_rules' );

添加重写规则

add_action('generate_rewrite_rules', 'yours_rewrite_rules' );

自己定义添加的query变量

add_action('query_vars', 'yours_query_vars');

路径重新定向的页面模板

add_action("template_redirect", 'yours_template_redirect');

重要的是,要将404状态改为200,重新路径定义模板后,WordPress会默认为404状态,这是需要将状态改为200后,再做模板判断。下面代码放置在yours_template_redirect中。

global $wp_rewrite;
//设置设置页面为真
$wp_query->is_page = true;
$wp_query->is_single = false;
$wp_query->is_home = false;
$wp_query->comments = false;

// 如果有404状态
if ($wp_query->is_404) {
	  // 设置404为假
	  unset($wp_query->query["error"]);
		$wp_query->query_vars["error"]="";
		$wp_query->is_404=false;
	  }
//改变页头的状态为200
header("HTTP/1.1 200 OK");
include(get_template_directory().'/custom/list_page_post.php');
die();
return;

自定义关键字和描述

简单说一下代码,这些代码是和项目息息相关的,所以独立出来可能大家一头雾水,简要的说明一下。

重写路径的样子为:/kunming/restaurants-and-dining_1396。

读取为:$category对应restaurants-and-dining,$location_id对应1396。
存放简介、标题、关键字和描述的格式为:简介||标题||关键字||描述。

读取用:explode(“||”,get_post_meta($location_id,’location_’.$category_s,true))[3]。
重写路径页的参数都是在yours_query_vars定义,在yours_rewrite_rules获得。

maps这个关键字被其他的占用了,所以用了一个maps_desc来代替,于是做了一个判断,如果是maps,就替换成maps_desc。
将“-”替换为“_”,原因是通过get_query_var获得的名称形式为yours-name,但数据表中存储位置的名字为yours_name,所以需要转换。

$location_id实际上是一篇文章的ID。所以,我们可以用get_post_meta读出’location_’.$category_s的值。用explode解析为数组。用strip_tags去除HTML标签。


add_action('wp_head','leaf_key_desc');
function leaf_key_desc() {
global $wp_query;
//获取自己重写路径页的参数
$reditect_page = $wp_query->query_vars['my_custom_page_type'];
$category = get_query_var('category');
$location_id = $wp_query->query_vars['location'];

$keywords = '';
$description = '';

//判断是否是重写路径的页面
if ($reditect_page == "list_page"){

//判断是否是maps路径
if ($category =='maps'){
$category_s=$category.'_desc';
}else{
$category_s=str_replace('-','_',$category);
}

//读取关键字和描述,用'||'隔开的值。0、1的位置分别存储的是简介和标题。
$keywords= strip_tags(explode("||",get_post_meta($location_id,'location_'.$category_s,true))[2]);
$description = strip_tags(explode("||",get_post_meta($location_id,'location_'.$category_s,true))[3]);

echo "\n";
if ( $keywords ) {
echo "<meta name=\"keywords\" content=\"$keywords\">\n";
}

if ( $description ) {
echo "<meta name=\"description\" content=\"$description\">\n";
}
}
}

将上面的代码放入functions.php中即可。

结束

你学会了吗?这代码是从项目中挖出来的,可能很难看懂。需要交流可以加群。

发表评论

邮箱地址不会被公开。 必填项已用*标注