• jhunlio

    (@jhunlio)


    I create a custom post type and it work find until I decided to change the permalink if my permalink look like this /blog/post-name it work find but if i change it to this /blog/category/post-name the page is not found.

    this is my code:

    // Add custom post page
    add_action( 'init', 'create_post_type' );
    function create_post_type() {
    register_post_type('blog', array(
    'label' => 'Blog',
    'public' => true,
    'show_ui' => true,
    'show_in_nav_menus' => false,
    'capability_type' => 'post',
    'hierarchical' => true,
    'rewrite' => array('slug' => 'blog/%cat%'),
    'menu_position' => 5,
    'with_front' => true,
    'taxonomies' => array('blog-cat'),
    'query_var' => true,
    'publicly_queryable' => true,
    'supports' => array('title', 'editor', 'thumbnail',
    )
    ) );
    }
    
    //Add new taxonomy upon WordPress initialization
    add_action( 'init', 'blog_create_taxonomies', 0 );
    
    function blog_create_taxonomies()
    {
        // Project Categories
        register_taxonomy('blog-cat',array('blog'),array(
            'hierarchical' => true,
            'label' => 'Blog Categories',
            'singular_name' => 'Blog Category',
            'show_ui' => true,
            'query_var' => 'blog-cat',
            'show_admin_column'     => true,
            'rewrite' => array('slug' => 'blog-cat', 'with_front' => true)
        ));
    }
    
    /*Filtro per modificare il permalink*/
    add_filter('post_link', 'cat_permalink', 1, 3);
    add_filter('post_type_link', 'cat_permalink', 1, 3);
    
    function cat_permalink($permalink, $post_id, $leavename) {
    	//con %brand% catturo il rewrite del Custom Post Type
        if (strpos($permalink, '%cat%') === FALSE) return $permalink;
            // Get post
            $post = get_post($post_id);
            if (!$post) return $permalink;
    
            // Get taxonomy terms
            $terms = wp_get_object_terms($post->ID, 'blog-cat');
            if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0]))
            	$taxonomy_slug = $terms[0]->slug;
            else $taxonomy_slug = 'no-cat';
    
        return str_replace('%cat%', $taxonomy_slug, $permalink);
    }
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘custom post type with category permalink (page not found)’ is closed to new replies.