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

问题描述 投票:0回答:1

我创建新的帖子类型并设置

'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 错误! 我的代码有什么问题?

php wordpress custom-post-type permalinks
1个回答
0
投票

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

'rewrite' => array(
'slug'  => 'd',
    'with_front'  => false,
  )
© www.soinside.com 2019 - 2024. All rights reserved.