将类别添加到固定链接中的自定义帖子类型

时间:2012-05-28 作者:hash

我知道以前有人问过这个问题,甚至还添加了自定义帖子类型,并为permalink重写。

问题是我有340个现有类别,我想继续使用。我以前可以看到/类别/子类别/postname

现在我有了customposttype/postname的slug。选择类别不再显示在permalink中。。。我没有将admin中的permalink设置更改为任何不同的设置。

我是否缺少一些东西或需要添加到此代码中?

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,
    )
);

4 个回复
SO网友:sanchothefat

添加自定义post类型重写规则时,有两个攻击点需要解决:

重写规则在中生成重写规则时会发生这种情况wp-includes/rewrite.php 在里面WP_Rewrite::rewrite_rules(). WordPress允许您过滤特定元素(如帖子、页面和各种类型的存档)的重写规则。你看到的地方posttype_rewrite_rules 这个posttype part应该是自定义帖子类型的名称。或者,您可以使用post_rewrite_rules 过滤,只要不删除标准post规则即可。

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

// 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;
}
如果你决定在这里玩游戏,最需要注意的是“漫游目录”布尔值。它为permastruct的每个段生成重写规则,并可能导致重写规则不匹配。当请求WordPress URL时,从上到下检查重写规则数组。一旦找到匹配项,它将加载它遇到的任何内容,例如,如果你的permastruct有一个贪婪的匹配项,例如/%category%/%postname%/ 和walk目录,它将为两者输出重写规则/%category%/%postname%//%category%/ 这将匹配任何东西。如果发生得太早,你就完蛋了

Permalinks是解析post类型Permalinks并将permastruct(例如“/%year%/%monthnum%/%postname%/”)转换为实际URL的函数。

下一部分是理想情况下的get_permalink() 在中找到函数wp-includes/link-template.php. 自定义post permalinks由生成get_post_permalink() 这是一个非常淡化的版本get_permalink(). get_post_permalink() 筛选依据post_type_link 所以我们用它来定制permastructure。

// 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;
}
如前所述,这是一个非常简单的生成自定义重写规则集和永久链接的案例,并不是特别灵活,但应该足以让您开始。

作弊我写了一个插件,可以让你为任何自定义帖子类型定义permastruct,但你可以使用%category% 在我的插件支持的帖子的permalink结构中%custom_taxonomy_name% 对于任何自定义分类法custom_taxonomy_name 是分类法的名称,例如。%club%.

它将像您所期望的那样适用于层次/非层次分类法。

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

SO网友:T.Todua

我找到了一个解决方案

(经过无休止的研究..我可以CUSTOM POST TYPE 永久链接,如:
example.com/category/sub_category/my-post-name

下面是代码(在functions.php或plugin中):

//===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;
}

SO网友:Varsha Dhadge

找到解决方案了!

要使自定义post类型具有层次结构永久链接,请安装自定义post类型永久链接(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\');
这条线让你的permalink工作

"cptp_permalink_structure" => "/%help_centre_category%/%post_id%-%postname%/",
您可以删除%post_id% 并且可以保持/%help_centre_category%/%postname%/"

别忘了冲洗仪表板上的永久链接。

SO网友:Jeremy Jared

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

<?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.

结束

相关推荐

GET_CATEGORIES类似wp_LIST_CATEGORIES的层次顺序-使用名称、插件和链接编辑CAT

我需要找到一种方法来列出所有类别-无论是否为空-在一个层次列表中-如wp\\U list\\U类别-还显示slug、cat名称和要在admin中编辑的链接。以下是我目前掌握的情况:$args = array( \'orderby\' => \'name\', \'order\' => \'ASC\', \'hide_empty\' => \'0\', ); $categ