WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Category Widget for Custom Post Types (2 posts)

  1. FeralReason
    Member
    Posted 2 months ago #

    I need a category widget for Custom Post Types. (The current widget only displays blog post categories.)

    Does anyone have suggestions for how to approach coding this -- or has anyone found a plugin that supports it?

  2. FeralReason
    Member
    Posted 2 months ago #

    I solved this by creating a widget (placed in a plugin) that queries wordpress tables and generates the appropriate category hyperlinks, based on my custom post type's taxonomy. I also created and registered a new widget area for a sidebar for my CPT-specific archives page. If you know (or can find out) how to do that, the remaining key issues are are:

    We are trying to duplicate the un-ordered list markup for the category links that the category widget ordinarily displays -- but we have to change the URL to create the right links for CPT categories. In my case, I created a CPT called "articles" and I registered my taxonomy like this:
    register_taxonomy( 'article-type' , 'articles' , $taxonomy_args );

    So whereas, if I were not using a CPT, the category link might have been:

    <a href="http://mysite/category/recipes" title="View all posts filed under Recipes">Recipes</a>

    With my CPT, that link is this:

    <a href="http://mysite/article-type/recipes" title="View all posts filed under Recipes">Recipes</a>

    Now, knowing that, we have to build query code that retrieves all of the CPT's "categories" (taxonomy = 'article-type') only where posts exist that are assigned those categories (count of posts is greater than 0).

    The query to do that is:

    $querystr = "
                   SELECT * FROM $wpdb->terms INNER JOIN $wpdb->term_taxonomy
                   ON $wpdb->terms.term_id = $wpdb->term_taxonomy.term_id
                   AND $wpdb->term_taxonomy.taxonomy = 'article-type'
                   AND $wpdb->term_taxonomy.count>'0'
    		";

    Most of the rest of the work is just grinding out the PHP that generates the UL code with its LIs and links, using the output from the query.

    Note that if you are working with a custom CPT archive page (and, if you got this far, you probably are), the results (when you click on the link) will show up instead on the default archive.php -- not your custom version. So, a copy of archive.php will have to be modified (within your child theme) if you want to show a sidebar with this "CPT category widget" in it. (Won't go into that - the solution is in another forum post.)

    At some point, I'll either write this up in an article or make the plugin public.

Reply

You must log in to post.

About this Topic