在自定义帖子类型详细信息页面的URL中添加术语插件

时间:2019-06-21 作者:Rigal

我创建了一个名为“movies”的自定义帖子类型,并添加了自定义分类法“Available for”,它包含两个术语

租金销售当前电影帖子详细信息页面URL

movies/avengers-endgame/
我想要像这样的URL

movies/sales/avengers-endgame/
movies/rent/avengers-endgame/
movies/{%selected term%}avengers-endgame/
任何人,请提出一个可能的解决方案来解决上述问题?

谢谢

1 个回复
最合适的回答,由SO网友:Chetan Vaghela 整理而成

您需要使用register\\u post\\u type函数在下面的一行中更新您已经注册了自定义post类型的位置。

\'rewrite\' => array(\'slug\' => \'movies/%cat%\')

要动态更改post类型的permalink,必须在函数中添加以下代码。php文件:

function change_link( $post_link, $id = 0 ) {
    $post = get_post( $id );
    if( $post->post_type == \'movies\' ) 
    {
       if ( is_object( $post ) ) {
          # assume that \'available-for\' is slug of your taxonomy 
          $terms = wp_get_object_terms( $post->ID, array(\'available-for\') );
          if ( $terms ) {
             return str_replace( \'%cat%\', $terms[0]->slug, $post_link );
         }
      }
    }
    return   $post_link ;
}
add_filter( \'post_type_link\', \'change_link\', 1, 3 );

//load the template on the new generated URL otherwise you will get 404\'s the page



   function generated_rewrite_rules() {
       add_rewrite_rule(
           \'^movies/(.*)/(.*)/?$\',
           \'index.php?post_type=movies&name=$matches[2]\',
           \'top\'
       );
    }
    add_action( \'init\', \'generated_rewrite_rules\' ); 
域。com/movies/{%selected term%}/avengers-endgame/要首先使用term,您必须对此进行更改。

\'rewrite\' => array(\'slug\' => \'%cat%/movies\')

function change_link( $post_link, $id = 0 ) {
    $post = get_post( $id );
    if( $post->post_type == \'movies\' ) 
    {
       if ( is_object( $post ) ) {
          # assume that \'available-for\' is slug of your taxonomy 
          $terms = wp_get_object_terms( $post->ID, array(\'available-for\') );
          if ( $terms ) {
             return str_replace( \'%cat%\', $terms[0]->slug, $post_link );
         }
      }
    }
    return   $post_link ;
}
add_filter( \'post_type_link\', \'change_link\', 1, 3 );

function movie_cpt_generating_rule($wp_rewrite) {
    $rules = array();
    $terms = get_terms( array(
        \'taxonomy\' => \'available-for\',
        \'hide_empty\' => false,
    ) );

$post_type = \'movies\';
foreach ($terms as $term) {    

    $rules[ $term->slug .\'/movies/([^/]*)$\'] = \'index.php?post_type=\' . $post_type. \'&movies=$matches[1]&name=$matches[1]\';

}
// merge with global rules
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter(\'generate_rewrite_rules\', \'movie_cpt_generating_rule\');
之后,需要刷新重写永久链接,转到wp-admin > Settings > permalinks. 只需使用“保存更改”按钮更新永久链接设置。

它将返回如下URL:

域。com/{%selected term%}/电影/复仇者结局/谢谢!

相关推荐