重写URL-将自定义变量作为目录路径插入

时间:2016-01-14 作者:Cristian Porta

我正试图在WordPress中用我自己的自定义url为Divi主题“project”重写permalink结构

我已经将“Divi slug”从“project”更改为“prodotti”,因此当前,URL如下所示:

http://www.example.com/prodotti/%postname%/
使用我的自定义功能

function custom_post_name() {
    return array(
        \'feeds\' => true,
        \'slug\' => \'prodotti\',
        \'with_front\' => false,
    );
}
add_filter(\'et_project_posttype_rewrite_args\', \'custom_post_name\');
我想add to these urls a variable, that reside for each post in post_metadata, 为了构建url,如:

http://www.example.com/prodotti/<mypostoptionvalue>/%postname%/
例如:

http://www.example.com/prodotti/AEX1102/%postname%/
http://www.example.com/prodotti/AEX1103/%postname%/
http://www.example.com/prodotti/AEX1104/%postname%/
有没有办法实现这种行为?

我做了很多测试,{$permastruct}_rewrite_rules, page_rewrite_rules, post_rewrite_rules 更多信息,从以下方面开始:https://codex.wordpress.org/Class_Reference/WP_Rewrite 没有结果。

1 个回复
SO网友:JimboSlice

我想你应该这样做:

add_action(\'init\', \'my_rewrite\');
function my_rewrite() {
  global $wp_rewrite;
  // Your desired structure
  $permalink_structure = \'/prodotti/%my_custom_variable%/%postname%/\'
  // add the custom variable to wp_rewrite tags
  $wp_rewrite->add_rewrite_tag("%my_custom_variable%", \'([^/]+)\', "my_custom_variable=");
  // Here you need to know the name of the custom post type you want the permalink structure to be used on
  $wp_rewrite->add_permastruct(\'custom_post_type_name\', $permalink_structure, false);
}
这应该会更改post类型的permalink结构。如果您现在访问一个名为“foobar”(在wp admin中)的帖子,它应该显示以下内容的永久链接:

/prodotti/%my_custom_variable%/foobar/
您现在需要做的就是通过挂钩“post\\u type\\u link”截获永久链接创建,并将字符串“%my\\u custom\\u variable%”替换为您想要的任何内容,如下所示:

add_filter(\'post_type_link\', \'intercept_permalink\', 10, 3);
function intercept_permalink ($permalink, $post, $leavename) {
  //check if current permalink has our custom variable
  if ( strpos($permalink, \'%my_custom_variable%\') !== false ) {
    //get this post\'s meta data with $post->ID
    $my_str = get_post_meta($post->ID, \'meta_key\');
    //maybe check if post meta data is legit and perhaps have some kind of fallback if it\'s empty or something
    //Then we just replace the custom variable string with our new string
    $permalink = str_replace(\'%my_custom_variable%\', strtolower($my_str), $permalink);
  }
  return $permalink;
}
我还没有测试过这个特定的代码,但我最近在我的一个项目中做过类似的事情

相关推荐