在永久链接中为自定义帖子类型添加类别


22

我知道人们以前已经问过这个问题,并且甚至添加了自定义帖子类型,并为永久链接进行了重写。

问题是我想继续使用340个现有类别。我曾经能够看到/ category / subcategory / postname

现在,我有一个customposttype / postname的标签。选择类别不再显示在永久链接中...我没有将admin中的永久链接设置更改为其他任何内容。

是否有我缺少的内容或需要添加到此代码中的内容?

function jcj_club_post_types() {
    register_post_type( 'jcj_club', array(
        'labels' => array(
            'name' => __( 'Jazz Clubs' ),
            'singular_name' => __( 'Jazz Club' ),
            'add_new' => __( 'Add New' ),
            'add_new_item' => __( 'Add New Jazz Club' ),
            'edit' => __( 'Edit' ),
            'edit_item' => __( 'Edit Jazz Clubs' ),
            'new_item' => __( 'New Jazz Club' ),
            'view' => __( 'View Jazz Club' ),
            'view_item' => __( 'View Jazz Club' ),
            'search_items' => __( 'Search Jazz Clubs' ),
            'not_found' => __( 'No jazz clubs found' ),
            'not_found_in_trash' => __( 'No jazz clubs found in Trash' ),
            'parent' => __( 'Parent Jazz Club' ),
        ),
        'public' => true,
        'show_ui' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'menu_position' => 5,
        'query_var' => true,
        'supports' => array( 
            'title',
            'editor',
            'comments',
            'revisions',
            'trackbacks',
            'author',
            'excerpt',
            'thumbnail',
            'custom-fields',
        ),
        'rewrite' => array( 'slug' => 'jazz-clubs-in', 'with_front' => true ),
        'taxonomies' => array( 'category','post_tag'),
        'can_export' => true,
    )
);

2
这可能是一个愚蠢的问题,但是您是否刷新了重写内容?
kristina childs

最近,我面临这个问题。解决了![#188834] [1] [1]:wordpress.stackexchange.com/questions/94817/...
maheshwaghmare

Answers:


16

添加自定义帖子类型重写规则时,有两个攻击要点:

改写规则

wp-includes/rewrite.php中生成重写规则时会发生这种情况WP_Rewrite::rewrite_rules()。WordPress允许您过滤特定元素(例如帖子,页面和各种类型的存档)的重写规则。您看到posttype_rewrite_rulesposttype部分应该是您的自定义帖子类型的名称。另外,您也可以使用post_rewrite_rules过滤器,只要您也不会删除标准发布规则。

接下来,我们需要该函数实际生成重写规则:

// add our new permastruct to the rewrite rules
add_filter( 'posttype_rewrite_rules', 'add_permastruct' );

function add_permastruct( $rules ) {
    global $wp_rewrite;

    // set your desired permalink structure here
    $struct = '/%category%/%year%/%monthnum%/%postname%/';

    // use the WP rewrite rule generating function
    $rules = $wp_rewrite->generate_rewrite_rules(
        $struct,       // the permalink structure
        EP_PERMALINK,  // Endpoint mask: adds rewrite rules for single post endpoints like comments pages etc...
        false,         // Paged: add rewrite rules for paging eg. for archives (not needed here)
        true,          // Feed: add rewrite rules for feed endpoints
        true,          // For comments: whether the feed rules should be for post comments - on a singular page adds endpoints for comments feed
        false,         // Walk directories: whether to generate rules for each segment of the permastruct delimited by '/'. Always set to false otherwise custom rewrite rules will be too greedy, they appear at the top of the rules
        true           // Add custom endpoints
    );

    return $rules;
}

如果决定玩转,这里需要注意的主要是“ Walk directory”布尔值。它为永久结构的每个段生成重写规则,并且可能导致重写规则不匹配。当请求WordPress URL时,将从顶部到底部检查重写规则数组。一旦找到匹配项,它将加载遇到的所有内容,例如,如果您的永久对象有贪婪的匹配项,例如。for /%category%/%postname%/和walk目录位于其上,将为两个/%category%/%postname%/AND 输出/%category%/匹配任何内容的重写规则。如果那太早发生了,那您就被搞砸了。

固定链接

该函数用于解析帖子类型的永久链接,并将永久结构(例如'/%year%/%monthnum%/%postname%/')转换为实际的URL。

下一部分是一个简单的示例,该示例理想地是在中get_permalink()找到的函数的版本wp-includes/link-template.php。生成自定义帖子永久链接,get_post_permalink()这是的精简版本get_permalink()get_post_permalink()被过滤,post_type_link因此我们使用它来创建自定义的永久结构。

// parse the generated links
add_filter( 'post_type_link', 'custom_post_permalink', 10, 4 );

function custom_post_permalink( $permalink, $post, $leavename, $sample ) {

    // only do our stuff if we're using pretty permalinks
    // and if it's our target post type
    if ( $post->post_type == 'posttype' && get_option( 'permalink_structure' ) ) {

        // remember our desired permalink structure here
        // we need to generate the equivalent with real data
        // to match the rewrite rules set up from before

        $struct = '/%category%/%year%/%monthnum%/%postname%/';

        $rewritecodes = array(
            '%category%',
            '%year%',
            '%monthnum%',
            '%postname%'
        );

        // setup data
        $terms = get_the_terms($post->ID, 'category');
        $unixtime = strtotime( $post->post_date );

        // this code is from get_permalink()
        $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;
            }
        }

        $replacements = array(
            $category,
            date( 'Y', $unixtime ),
            date( 'm', $unixtime ),
            $post->post_name
        );

        // finish off the permalink
        $permalink = home_url( str_replace( $rewritecodes, $replacements, $struct ) );
        $permalink = user_trailingslashit($permalink, 'single');
    }

    return $permalink;
}

如前所述,这是用于生成自定义重写规则集和永久链接的非常简化的情况,虽然不是特别灵活,但是足以让您入门。

作弊

我写了一个插件,可以让您为任何自定义帖子类型定义%category%永久结构,但是就像您可以在永久链接结构中使用的那样,我的插件也支持%custom_taxonomy_name%您拥有的任何自定义分类法的帖子custom_taxonomy_name,例如,分类法名称在哪里。%club%

它将与分层/非分层分类法一样工作。

http://wordpress.org/extend/plugins/wp-permastructure/


1
插件很棒,但是如果没有插件,您能解释一下如何解决问题吗?
Eugene Manuilov

我同意有一个插件来解决这个问题是很棒的(我将它加为书签,这是我首先问到的这个问题),但是答案将从简要说明问题是什么以及插件如何克服它中受益。:)
Rarst

@EugeneManuilov好吧,很抱歉,这是一个冗长的答案。这就是我的基本知识!
sanchothefat 2012年

看起来第一个$permalink = home_url(...被覆盖$permalink = user_trailingslashit(...并且从未使用过。还是我错过了什么?$post_link甚至没有定义。应该是$permalink = user_trailingslashit( $permalink, 'single' );吗?
伊恩·邓恩

好的收获,应该$permalink不会$post_link。干杯:)
sanchothefat

1

得到了解决方案!

要具有用于自定义帖子类型的分层永久链接,请安装“自定义帖子类型永久链接”(https://wordpress.org/plugins/custom-post-type-permalinks/)插件。

更新注册的帖子类型。我有帖子类型的名称作为帮助中心

function help_centre_post_type(){
    register_post_type('helpcentre', array( 
        'labels'            =>  array(
            'name'          =>      __('Help Center'),
            'singular_name' =>      __('Help Center'),
            'all_items'     =>      __('View Posts'),
            'add_new'       =>      __('New Post'),
            'add_new_item'  =>      __('New Help Center'),
            'edit_item'     =>      __('Edit Help Center'),
            'view_item'     =>      __('View Help Center'),
            'search_items'  =>      __('Search Help Center'),
            'no_found'      =>      __('No Help Center Post Found'),
            'not_found_in_trash' => __('No Help Center Post in Trash')
                                ),
        'public'            =>  true,
        'publicly_queryable'=>  true,
        'show_ui'           =>  true, 
        'query_var'         =>  true,
        'show_in_nav_menus' =>  false,
        'capability_type'   =>  'page',
        'hierarchical'      =>  true,
        'rewrite'=> [
            'slug' => 'help-center',
            "with_front" => false
        ],
        "cptp_permalink_structure" => "/%help_centre_category%/%post_id%-%postname%/",
        'menu_position'     =>  21,
        'supports'          =>  array('title','editor', 'thumbnail'),
        'has_archive'       =>  true
    ));
    flush_rewrite_rules();
}
add_action('init', 'help_centre_post_type');

这是注册分类法

function themes_taxonomy() {  
    register_taxonomy(  
        'help_centre_category',  
        'helpcentre',        
        array(
            'label' => __( 'Categories' ),
            'rewrite'=> [
                'slug' => 'help-center',
                "with_front" => false
            ],
            "cptp_permalink_structure" => "/%help_centre_category%/",
            'hierarchical'               => true,
            'public'                     => true,
            'show_ui'                    => true,
            'show_admin_column'          => true,
            'show_in_nav_menus'          => true,
            'query_var' => true
        ) 
    );  
}  
add_action( 'init', 'themes_taxonomy');

这行使您的永久链接起作用

"cptp_permalink_structure" => "/%help_centre_category%/%post_id%-%postname%/",

您可以删除%post_id%并可以保留/%help_centre_category%/%postname%/"

不要忘记从仪表板清除永久链接。


+1最简单的解决方案是只使用此插件:wordpress.org/plugins/custom-post-type-permalinks完美运行
Jules

是的,但是如果您有一个自定义帖子类型,但是如果您在一个主题中有多个自定义帖子类型,那么以上就是解决方案。此外,它还更改了与您的帖子类型信息相同的类别信息。
Varsha Dhadge

1

我找到了解决方案!!!

(经过无休止的研究。。我可以使用“ 自定义帖子类型”永久链接,例如:
example.com/category/sub_category/my-post-name

此处的代码(在functions.php或插件中):

//===STEP 1 (affect only these CUSTOM POST TYPES)
$GLOBALS['my_post_typesss__MLSS'] = array('my_product1','....');

//===STEP 2  (create desired PERMALINKS)
add_filter('post_type_link', 'my_func88888', 6, 4 );

function my_func88888( $post_link, $post, $sdsd){
    if (!empty($post->post_type) && in_array($post->post_type, $GLOBALS['my_post_typesss']) ) {  
        $SLUGG = $post->post_name;
        $post_cats = get_the_category($id);     
        if (!empty($post_cats[0])){ $target_CAT= $post_cats[0];
            while(!empty($target_CAT->slug)){
                $SLUGG =  $target_CAT->slug .'/'.$SLUGG; 
                if  (!empty($target_CAT->parent)) {$target_CAT = get_term( $target_CAT->parent, 'category');}   else {break;}
            }
            $post_link= get_option('home').'/'. urldecode($SLUGG);
        }
    }
    return  $post_link;
}

// STEP 3  (by default, while accessing:  "EXAMPLE.COM/category/postname"
// WP thinks, that a standard post is requested. So, we are adding CUSTOM POST
// TYPE into that query.
add_action('pre_get_posts', 'my_func4444',  12); 

function my_func4444($q){     
    if ($q->is_main_query() && !is_admin() && $q->is_single){
        $q->set( 'post_type',  array_merge(array('post'), $GLOBALS['my_post_typesss'] )   );
    }
    return $q;
}

-2

您的代码有几个错误。我清理了您现有的代码:

<?php
function jcj_club_post_types() {
  $labels = array(
    'name' => __( 'Jazz Clubs' ),
    'singular_name' => __( 'Jazz Club' ),
    'add_new' => __( 'Add New' ),
    'add_new_item' => __( 'Add New Jazz Club' ),
    'edit' => __( 'Edit' ),
    'edit_item' => __( 'Edit Jazz Clubs' ),
    'new_item' => __( 'New Jazz Club' ),
    'view' => __( 'View Jazz Club' ),
    'view_item' => __( 'View Jazz Club' ),
    'search_items' => __( 'Search Jazz Clubs' ),
    'not_found' => __( 'No jazz clubs found' ),
    'not_found_in_trash' => __( 'No jazz clubs found in Trash' ),
    'parent' => __( 'Parent Jazz Club' ),
    );
  $args = array(
    'public' => true,
    'show_ui' => true,
    'publicly_queryable' => true,
    'exclude_from_search' => false,
    'menu_position' => 5,
    'query_var' => true,
    'supports' => array( 'title','editor','comments','revisions','trackbacks','author','excerpt','thumbnail','custom-fields' ),
    'rewrite' => array( 'slug' => 'jazz-clubs-in', 'with_front' => true ),
    'has_archive' => true
    );
  register_post_type( 'jcj_club', $args );
  }
add_action( 'init','jcj_club_post_types' );
?>

用上面的代码替换您的代码,然后查看是否可行。如果您还有其他问题,请回信给我,我们会尽力帮助您。

编辑:

我注意到我被排除在外了'has_archive' => true

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.