permalink not working on custom post and category

2019-05-10 02:14发布

I am trying to add wordpress custom post type and category in wordpress

add_action( 'init', 'work_register' );   

function work_register() {   

$labels = array( 
    'name' => _x('Work', 'post type general name'), 
    'singular_name' => _x('Work Item', 'post type singular name'), 
    'add_new' => _x('Add New', 'work item'), 
    'add_new_item' => __('Add New Work Item'), 
    'edit_item' => __('Edit Work Item'), 
    'new_item' => __('New Work Item'), 

    'view_item' => __('View Work Item'), 
    'search_items' => __('Search Work'), 
    'not_found' => __('Nothing found'), 
    'not_found_in_trash' => __('Nothing found in Trash'), 
    'parent_item_colon' => '' 
);   

$args = array( 
    'labels' => $labels, 
    'public' => true, 
    'publicly_queryable' => true, 
    'show_ui' => true, 
    'query_var' => true, 
    'menu_icon' => get_stylesheet_directory_uri() . '/article16.png', 
    'rewrite' => array( 'slug' => 'work', 'with_front'=> false ), 
    'capability_type' => 'post', 
    'hierarchical' => true,
    'has_archive' => true,  
    'menu_position' => null, 
    'supports' => array('title','editor','thumbnail') 
);   

register_post_type( 'work' , $args ); 

register_taxonomy( 'categories', array('work'), array(
    'hierarchical' => true, 
    'label' => 'Categories', 
    'singular_label' => 'Category', 
    'rewrite' => array( 'slug' => 'categories', 'with_front'=> false )
    )
);

register_taxonomy_for_object_type( 'categories', 'work' );

}

My permalink structure is:

/%category%/%postname%/

When I am adding from post it is giving me link

  /category/postname

but when I am adding from custom post, it is giving me only

 /postname 

I want /category/postname in custom post also

Please suggest where I am wrong

标签: php wordpress
1条回答
We Are One
2楼-- · 2019-05-10 02:39

Change your rewrite to add the work post type query var:

'rewrite' => array('slug' => 'work/%categories%')

Then filter post_type_link to insert the selected categories into the permalink:

function custom_work_post_link( $post_link, $id = 0 ){
    $post = get_post($id);  
    if ( is_object( $post ) ){
        $terms = wp_get_object_terms( $post->ID, 'work' );
        if( $terms ){
            return str_replace( '%categories%' , $terms[0]->slug , $post_link );
        }
    }
    return $post_link;  
}
add_filter( 'post_type_link', 'custom_work_post_link', 1, 3 );

There are also plugins like Custom Post Type Permalinks that can do this for you.

查看更多
登录 后发表回答