分享

wordpress 自定义类型与固定链接

 handup 2015-03-19

吃得乐美食分享网http://www.,运行了一段时间,朋友们说不错,为了继续丰富内容,就加上了自定义类型,然后为了链接更好看,就rewrite下,不想。。。
搞晕晕了几天,终于把自定义类型的固定链接搞定,事情经过是这样的

先拜访前辈啊(指的是这门技术,偶人已经很老了也,沦江湖,我是前辈:),此话不细表,请接着看重点)

找到了http://www./custom-post-type-permalink-code.html

  1. $mytypes = array(//根据需要添加你的自定义文章类型
  2. 	'type1' => 'slug1',
  3. 	'type2' => 'slug2',
  4. 	'type3' => 'slug3'
  5. 	);
  6. add_filter('post_type_link', 'my_custom_post_type_link', 1, 3);
  7. function my_custom_post_type_link( $link, $post = 0 ){
  8. 	global $mytypes;
  9. 	if ( in_array( $post->post_type,array_keys($mytypes) ) ){
  10. 		return home_url( $mytypes[$post->post_type].'/' . $post->ID .'.html' );
  11. 	} else {
  12. 		return $link;
  13. 	}
  14. }
  15. add_action( 'init', 'my_custom_post_type_rewrites_init' );
  16. function my_custom_post_type_rewrites_init(){
  17. 	global $mytypes;
  18. 	foreach( $mytypes as $k => $v ) {
  19. 		add_rewrite_rule(
  20. 			$v.'/([0-9]+)?.html$',
  21. 			'index.php?post_type='.$k.'&p=$matches[1]',
  22. 			'top' );
  23. 	}
  24. }

$labels = array(
   'name' => __( 'Field Groups', 'mop' ),
'singular_name' => __( 'Advanced Custom Fields', 'mop' ),
   'add_new' => __( 'Add New' , 'mop' ),
   'add_new_item' => __( 'Add New Field Group' , 'mop' ),
   'edit_item' =>  __( 'Edit Field Group' , 'mop' ),
   'new_item' => __( 'New Field Group' , 'mop' ),
   'view_item' => __('View Field Group', 'mop'),
   'search_items' => __('Search Field Groups', 'mop'),
   'not_found' =>  __('No Field Groups found', 'mop'),
   'not_found_in_trash' => __('No Field Groups found in Trash', 'mop'), 
);
register_post_type('share', array(
'labels' => $labels,
'public' => false,
'show_ui' => true,
'_builtin' =>  true,
'capability_type' => 'post',
'hierarchical' => true,
'rewrite' => true,
'query_var' => true,
'exclude_from_search'=>false,
'supports' => array( 'title'
),
'show_in_menu' => false,
));

然后改为自己定义的类型 (上面也是直接从acf拿过来的) ~~~~~~
  1. $mytypes = array(//根据需要添加你的自定义文章类型
  2. 	'share' => 'share',
  3. 	'type2' => 'slug2',
  4. 	'type3' => 'slug3'
  5. 	);
  6. add_filter('post_type_link', 'my_custom_post_type_link', 1, 3);
然后在前台输入 localhost/chidele/share/123.html

结果,傻眼,报404错误,找到页面。

一搜,要更新 wp的“rewrite”,可以用flush_rewrite_rules,也可进入“配置-固定链接”页面一下(不需要保存等等),就可以刷新.htaccess。

然后,那上然后,还是不行啊,404错误

多处 var_dump,原来与register_post_type有关系

'publicly_queryable' =>true,要不然index.php?post_type='.$k.'&p=$matches[1]不理你注册的类型,'_builtin' =>  false,否则会把你注册的类型按“内建类型”处理(按你在“设置->固定链接”设置的

弄完这些,就大功靠成了。


切慢,有个问题又让我折腾了半天,我本机环境是用wampserver搭建的,访问重写的地址,一直找不到,后来一搜索,原来需要配置rewrite_module modules/mod_rewrite.so为开启。AllowOverride None这一个没修改,也可以。

本地wampserver如何配置伪静态
分类: PHP学习
第一步:找到Apache安装目录下httpd.conf这个文件,搜索找到,“LoadModule rewrite_module modules/mod_rewrite.so”,找到这一行,去掉前面的“#”;
第二步:找到“AllowOverride None”改为“AllowOverride All”.;
第三步:重启apache

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多