0

Instead of using category listing templates for a site that I am working on, I am using ajax for filtering, searching, and listing all blog posts on the blog page. However, I need to add all the categories to the navigation, and when I do that, the link is, as expected, the default archive page for that category (ie. /category/my-category). Is there a way to forward that to the blog page (ideally, it would be whatever page is set as the blog page through the settings; not a specific URL) with a query string containing the category slug (ie. /blog/?category=my-category)? Or is there a better solution that still allows for a user to add categories to a menu through the menu admin?

1 Answer 1

0

Figured out the answer myself. Luckily, I had a lot of the requirements already set up and it was just a matter of piecing them together. I am using a custom nav walker, and the start_el function passes in an $item parameter that contains an object property, telling you what that nav item is (ie. a page, a custom link, or in our case, a category). I was able to use this information, along with a custom function I created for generating the category URL, to get the result I was looking for:

My_Nav_Walker.php

class My_Nav_Walker extends Walker_Nav_Menu {

    /* ... */

    function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        /* ... */
        $attributes = !empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) . '"' : '';

        $url = $item->url;

        if($item->object == "category") {
            $category = get_category($item->object_id);
            $url = get_category_url($category->slug);
        }

        $attributes .= !empty($url) ? ' href="' . esc_attr($url) . '"' : '';

        /* ... */

    }

    /* ... */
}

Custom Category URL Function

function get_category_url($category_slug) {
    return get_post_type_archive_link( 'post' ) . '?category=' . $category;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.