更改自定义帖子类型的永久链接

时间:2016-05-15 07:06:22

标签: wordpress custom-post-type permalinks

我创建新的帖子类型并设置'rewrite' => false然后设置我使用的新永久链接:

// add to our plugin init function
global $wp_rewrite;
$dariche_structure = '/d/%post_id%/%dariche%';
$wp_rewrite->add_rewrite_tag("%dariche%", '([^/]+)', "dariche=");
$wp_rewrite->add_permastruct('dariche', $dariche_structure, false);


// Add filter to plugin init function
add_filter('post_type_link', 'dariche_permalink', 10, 3);   
// Adapted from get_permalink function in wp-includes/link-template.php
function dariche_permalink($permalink, $post_id, $leavename) {
    $post = get_post($post_id);
    $rewritecode = array(
        '%year%',
        '%monthnum%',
        '%day%',
        '%hour%',
        '%minute%',
        '%second%',
        $leavename? '' : '%postname%',
        '%post_id%',
        '%category%',
        '%author%',
        $leavename? '' : '%pagename%',
    );

    if ( '' != $permalink && !in_array($post->post_status, array('draft', 'pending', 'auto-draft')) ) {
        $unixtime = strtotime($post->post_date);

        $category = '';
        if ( strpos($permalink, '%category%') !== false ) {
            $cats = get_the_category($post->ID);
            if ( $cats ) {
                usort($cats, '_usort_terms_by_ID'); // order by ID
                $category = $cats[0]->slug;
                if ( $parent = $cats[0]->parent )
                    $category = get_category_parents($parent, false, '/', true) . $category;
            }
            // show default category in permalinks, without
            // having to assign it explicitly
            if ( empty($category) ) {
                $default_category = get_category( get_option( 'default_category' ) );
                $category = is_wp_error( $default_category ) ? '' : $default_category->slug;
            }
        }

        $author = '';
        if ( strpos($permalink, '%author%') !== false ) {
            $authordata = get_userdata($post->post_author);
            $author = $authordata->user_nicename;
        }

        $date = explode(" ",date('Y m d H i s', $unixtime));
        $rewritereplace =
        array(
            $date[0],
            $date[1],
            $date[2],
            $date[3],
            $date[4],
            $date[5],
            $post->post_name,
            $post->ID,
            $category,
            $author,
            $post->post_name,
        );
        $permalink = str_replace($rewritecode, $rewritereplace, $permalink);
    } else { // if they're not using the fancy permalink option
    }
    return $permalink;
}

我的新帖子类型名称为dariche。 我在所有帖子设置中的默认永久链接是:article/%post_id%/%postname%/

现在,我的新帖子类型的永久链接是d/%post_id%/%postname%/。但它不起作用,只显示404错误!我的代码有什么问题?

1 个答案:

答案 0 :(得分:0)

似乎您只想更改新帖子类型永久链接的基础。你可以通过设置重写来实现这一目标。注册帖子类型时。

'rewrite' => array(
'slug'  => 'd',
    'with_front'  => false,
  )