[![修改Woocommerce商品固定链接其它自定义文章类型适用](https://pic.salongweb.com/2015/07/custom-post-type-permalink.jpg)](https://pic.salongweb.com/2015/07/custom-post-type-permalink.jpg "修改Woocommerce商品固定链接其它自定义文章类型适用")在更新[Concise主题](https://api.salongweb.com/product/concise.html)时集成了前端用户中心和商城插件，发现插件中为商城产品文章设置好了固定链接，所以把萨龙网络的作品集与商城的两种自定义类型的文章固定链接添加上。

自定义文章类型固定链接可设置两形式，分别为ID和别名，萨龙龙认为使用别名的方式再加适合SEO，不过两种方式代码都已经放上。很多主题也会有两种或两种以上的自定义类型文章，为文章类型添加一个数组就可以，这样不论多少种自定义文章类型都适合。

**自定义文章类型固定链接：别名形式**

1. $posttypes = array(
2. ‘product’ =&gt; ‘product’,//Woocommerce产品自定义文章类型
3. ‘portfolio’ =&gt; ‘portfolio’//作品集自定义文章类型
4. );
5. add\_filter(‘post\_type\_link’, ‘custom\_book\_link’, 1, 3);
6. function custom\_book\_link( $link, $post = 0 ){
7. global $posttypes;
8. if ( in\_array( $post-&gt;post\_type,array\_keys($posttypes) ) ){
9. return home\_url( $posttypes\[$post-&gt;post\_type\].’/’ . $post-&gt;post\_name .’.html’ );
10. } else {
11. return $link;
12. }
13. }
14. add\_action( ‘init’, ‘custom\_book\_rewrites\_init’ );
15. function custom\_book\_rewrites\_init(){
16. global $posttypes;
17. foreach( $posttypes as $k =&gt; $v ) {
18. add\_rewrite\_rule(
19. $v.’/(\[一-龥a-zA-Z0-9\_-\]+)?.html(\[sS\]\*)?$’,
20. ‘index.php?post\_type=’.$k.’&amp;name=$matches\[1\]’,
21. ‘top’ );
22. }
23. }

**自定义文章类型固定链接：ID形式**

1. $posttypes = array(
2. ‘product’ =&gt; ‘product’,//Woocommerce产品自定义文章类型
3. ‘portfolio’ =&gt; ‘portfolio’//作品集自定义文章类型
4. );
5. add\_filter(‘post\_type\_link’, ‘custom\_book\_link’, 1, 3);
6. function custom\_book\_link( $link, $post = 0 ){
7. global $posttypes;
8. if ( in\_array( $post-&gt;post\_type,array\_keys($posttypes) ) ){
9. return home\_url( $posttypes\[$post-&gt;post\_type\].’/’ . $post-&gt;ID .’.html’ );
10. } else {
11. return $link;
12. }
13. }
14. add\_action( ‘init’, ‘custom\_book\_rewrites\_init’ );
15. function custom\_book\_rewrites\_init(){
16. global $posttypes;
17. foreach( $posttypes as $k =&gt; $v ) {
18. add\_rewrite\_rule(
19. $v.’/(\[0-9\]+)?.html$’,
20. ‘index.php?post\_type=’.$k.’&amp;p=$matches\[1\]’,
21. ‘top’ );
22. }
23. }

两种形式的固定链接代码也只是设置了显示方式以及显示的内容，ID就显示0-9其中的数字，别名就显示所有的字符。

**使用固定链接后，Purity主题中集成的作品集文章类型在文章页面获取作品集分类名称和SEO中获取产品关键字时获取不了，不使用固定是正常，所以Google找到应对方案。**

1、作品集文章页面获取分类名称，添加到作品集文章页面中

1. &lt;!–获取作品集分类名称–&gt;
2. &lt;?php
3. $terms = get\_the\_terms($post-&gt;ID, ‘portfolio\_field’ );//portfolio\_field为作品集分类法
4. if ($terms &amp;&amp; ! is\_wp\_error($terms)) :
5. $term\_names\_arr = array();
6. foreach ($terms as $term) {
7. $term\_names\_arr\[\] = $term-&gt;name;
8. }
9. $terms\_name\_str = join( “,”, $term\_names\_arr);
10. endif;
11. ?&gt;
12. &lt;!–获取作品集分类名称end–&gt;

2、使用以下代码来调用分类名称

1. &lt;?php echo $terms\_name\_str; ?&gt;

通过上面的代码我们可以获取portfolio\_field的分类名称，获取产品关键字名称也同样适用，将上面代码中的portfolio\_field修改为product-tag即可。

\[successbox\]设置好自定义文章类型的固定链接，看着确实很舒服，也有利于SEO，同时也解决设置固定链接后与其它代码产生的冲突。\[/successbox\]