WordPress child categories not working in urls like they should

倾然丶 夕夏残阳落幕 提交于 2019-12-13 06:15:34

问题


I am using this plugin called, "Custom Post Type Permalinks", which kinda helps me to get a post type to line up with a custom taxonomy that I created called, product_category, but I can't get the product_category taxonomy links proper with /shop/ in front of them that work with Child Categories also.

Basically, the custom post type is product and has a url structure like so: /shop/category/{Category Parent}/{Category Child}/{Product Name} and looks like the following in functions.php when registering the custom post type:

register_post_type('product', array(
        'description'           => __('Products'),
        'label'                 => __('products'),
        'labels'                => array(
            'name'                  => _x('Product', 'Post Type General Name'),
            'singular_name'         => _x('Product', 'Post Type Singular Name'),
            'menu_name'             => __('Products'),
            'parent_item_colon'     => __('Parent Product'),
            'all_items'             => __('All Products'),
            'view_item'             => __('View Product'),
            'add_new_item'          => __('Add New Product'),
            'add_new'               => __('Add New'),
            'edit_item'             => __('Edit Product'),
            'update_item'           => __('Update Product'),
            'search_items'          => __('Search Product'),
            'not_found'             => __('Not Found'),
            'not_found_in_trash'    => __('Not Found in Trash')
        ),
        'taxonomies'            => array('product_category'),
        'supports'              => array('title', 'editor', 'thumbnail'),
        'rewrite'               =>  array('slug' => 'shop', 'with_front' => false),
        "cptp_permalink_structure" => "/category/%product_category%/%postname%/",
        'hierarchical'          => false,
        'public'                => true, // Needs to be set to true to be able to show the endpoints!
        'show_ui'               => true,
        'show_in_menu'          => true,
        'show_in_nav_menus'     => false,
        'show_in_admin_bar'     => true,
        'query_var'             => true,
        'menu_position'         => 10,
        'menu_icon'             => 'dashicons-cart',
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page'
    )
);

The cptp_permalink_structure key allows me to assign %product_category% so that the categories (parent and children) are collected in the url and the product name is the last part of the path. I needed to give this a slug, so I choose shop so that it has something as the slug and shop should come before category anyways. All of the Product urls are working perfectly fine. And look like this: /shop/category/{Category Parent}/{Category Child}/{Product Name}/

Now for the custom taxonomy, I added within the function that gets triggered by the init action of WordPress and looks like this:

// I do not want to use 'category' since I don't want post categories mixed with product categories.
register_taxonomy('product_category', 'product', array(
    'label' => __('Category'),
    'rewrite' => array('slug' => 'shop/category', 'hierarchical' => true, 'with_front' => false),
    'labels' => array(
        'name' => __('Categories'),
        'singular_name' => __('Category'),
        'all_items' => __('All Categories'),
        'edit_item' => __('Edit Category'),
        'view_item' => __('View Category'),
        'update_item' => __('Update Category'),
        'add_new_item' => __('Add New Category'),
        'new_item_name' => __('New Category Name'),
        'parent_item' => __('Parent Category'),
        'parent_item_colon' => __('Parent Category:'),
        'search_items' => __('Search Categories'),
        'popular_items' => __('Popular Categories'),
        'separate_items_with_commas' => __('Separate Categories with commas'),
        'add_or_remove_items' => __('Add or Remove Categories'),
        'choose_from_most_used' => __('Choose from the most used Categories'),
        'not_found' => __('No Categories found')
    ),
    'public' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'hierarchical' => true,
    'exclude_from_search'   => false,
    'description' => 'Categories associated with Products.',
    'query_var' => true,
    'capabilities' => array(
        'manage_terms' => 'manage_options', //by default only admin
        'edit_terms' => 'manage_options',
        'delete_terms' => 'manage_options',
        'assign_terms' => 'edit_posts'  // means administrator', 'editor', 'author', 'contributor'
    )
));

I've tried using shop/category for the rewrite slug of the taxonomy (as you can see above), which would be perfect, if only child category archive pages were not producing 404 pages. So while: /shop/category/{Category Parent}/ and /shop/category/{Category Child}/ works, /shop/category/{Category Parent}/{Category Child}/ returns a 404 Error page. So, I'm at a loss on how to get Child Categories showing as in /shop/category/{Category Parent}/{Category Child}/

Note: If I change to just category as the rewrite slug, Children Categories are lining up properly like so: /category/{Category Parent}/{Category Child}, but the problem is, I need /shop/ before /category/ here.

How to do this? Been trying to figure this out for days now, with tons of different ways, tried adding a rewrite rule also (when changing the rewrite slug to just category).

add_rewrite_rule('shop/category/?([^/]*)', 'index.php?product_category=$matches[1]', 'top');

But the rewrite rule doesn't work for Child Categories either. And returns the parent category archive instead of the child.

As I've tested this within the archive.php file with the following code:

$tax_slug = get_query_var('product_category');
echo '<pre>', var_dump($tax_slug), '</pre>';

And returns the parent category slug instead of the child on child categories.

Any help is appreciated here, I've been pulling my hair out... going bald!

EDIT - Possible Method that might work

So, basically, it might be as simple as creating another BASE for that taxonomy in the Permalinks section of the admin. But how to create a BASE for a custom taxonomy? There is already a BASE for categories and tags, but if this could work, I would need a BASE for product_category, and the slug for the product_category taxonomy could just be category, and the BASE would add shop before it for all links. But how to create a BASE for a custom taxonomy?


回答1:


I think you should update the query argument in functions.php. I tried your code in my local installation and it worked fine with mine.

The updated code for this is :

/* Have WordPress match postname to any of our public post types (post, page, product)
 * All of our public post types can have /post-name/ as the slug, so they better be unique across all posts
 * By default, core only accounts for posts and pages where the slug is /post-name/
 */

function na_parse_request( $query ) {

     if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
     }

     if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'post', 'page', 'product' ) );
     }
}
add_action( 'pre_get_posts', 'na_parse_request' );

This basically changes the query string when you update any changes to the permalink and rewrite rules. Here you post type value "product" has been given to set query.

Hope this will work for you.

Thank You




回答2:


Figured it out after looking at the dump of rules from the rewrite_rules_array filter.

I added in this bit in the wordpress init action and now works:

add_rewrite_rule('shop/category/(.+?)/?$', 'index.php?product_category=$matches[1]&cpage=$matches[2]', 'top');

Thanks to all for your help with this. The slug for the custom taxonomy is the same at: shop/category

The important thing here in order to get child categories working is this bit: &cpage=$matches[2] which I wan't aware of and also didn't even know the name of the child category was cpage, this was discovered while looking at the rewrite_rules_array output which I just dumped on the page to see.



来源:https://stackoverflow.com/questions/42340058/wordpress-child-categories-not-working-in-urls-like-they-should

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!