具有不起作用的元值的自定义固定链接。为什么?

时间:2015-12-05 作者:Blackbam

下面的代码应该可以工作,但不能工作(没有激活插件)。在后端,将正确显示自定义帖子类型的永久链接,但如果在前端调用,将显示不正确的帖子。

但是,如果永久链接被禁用,它会工作:

// register post type
add_action(\'init\',\'register_item\');

function register_item() {


  register_post_type( \'hebamme\',
    array(
      \'labels\' => array(
        \'name\' => __( \'Hebammen\' ), //this name will be used when will will call the investments in our theme
        \'singular_name\' => __( \'Hebamme\' ),
      ),
      \'description\' => \'\',
        \'public\' => true,
      \'show_ui\' => true,
      \'hierarchical\' => false, //it means we cannot have parent and sub pages
      \'capability_type\' => \'post\', //will act like a normal post
      \'rewrite\' => array(\'slug\' => \'hebammen\',\'with_front\'=>true), //this is used for rewriting the permalinks
      \'query_var\' => true,
      \'supports\' => array( \'title\', \'editor\', \'revisions\',\'custom-fields\'), //the editing regions that will support
      \'menu_position\' => 5
    )
  );
}

// Permalinks
add_action(\'init\', \'smc_add_rewrite_rules\');

function smc_add_rewrite_rules() {
    // Register custom rewrite rules
    global $wp_rewrite;

    $wp_rewrite->add_rewrite_tag(\'%location%\', \'([^/]+)\', \'location=\');
    $wp_rewrite->add_rewrite_tag(\'%pmcustom%\', \'([^/]+)\', \'pmcustom=\');
    $wp_rewrite->add_permastruct(\'hebamme\', \'/hebammen/%location%/%pmcustom%/\',false);


}

add_filter(\'post_type_link\', \'smc_permalinks\', 10, 3);

function smc_permalinks($permalink, $post, $leavename) {

    $no_data = \'na\';
    $post_id = $post->ID;
    if($post->post_type != \'hebamme\' || empty($permalink) || in_array($post->post_status, array(\'draft\', \'pending\', \'auto-draft\'))) {
         return $permalink;
    }

    $var1 = get_post_meta($post_id, \'sc_heb_city\', true);
    $var1 = sanitize_title($var1);

    if(!$var1) { 
        $var1 = $no_data; 
    }
    return str_replace(\'%pmcustom%\',$post->post_name,str_replace(\'%location%\', $var1, $permalink));
}

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

将投递类型注册中的重写段改为hebammen/%location%

删除整个smc_add_rewrite_rules 作用

将筛选器添加到query_vars 注册location 查询变量更改smc_permalinks 仅替换的函数%location%, 将自动插入postname

相关推荐

Post with Custom Permalinks

我的永久链接设置如下:http://myblog.com/%category%/%postname%/一切正常。但我正在寻找一种方法,只为一些帖子(10-11篇帖子)设置如下永久链接。http://myblog.com/%postname%/我之所以要这样做,是因为我正在合并两个WordPress网站,我不想失去另一个网站的帖子,这些帖子已经以旧的permalink结构发布在Facebook等网站上。