• Resolved Alpha Plus

    (@alpha-plus)


    I posted this in the ‘Themes and Templates’ forum here but think I may have been in the wrong forum.

    I’ve figured out most of what I was trying to do in that post, but I’m having difficulty finding out how to echo the slug of the current post category.

    I have some default text.. e.g. “About | More from this category” and want to link them to different pages based on each category’s slug.. e.g. https://example.com/about/slug

    I should mention that this is a custom post type so the taxonomy i’m looking for is download_category

    [Moderator Note: No bumping. If it’s that urgent, consider hiring someone instead.]

Viewing 4 replies - 1 through 4 (of 4 total)
  • You may be able to use the get_category_by_slug() and get_category_link() functions.

    Thread Starter Alpha Plus

    (@alpha-plus)

    Thanks vtxyzzy.. The problem is that it’s a custom post type, so all the get_category commands don’t work. Apparently they only work with the regular blog posts.

    The get_term commands are what I think I’m supposed to be using, but I still can’t get it to spit out a ‘slug’

    The functions that take a post id should work on custom post types. For example, 585 is the ID of a CPT post, and this works for me:

    $id = 585;
    $cats = get_the_category($id);
    echo "The slug is {$cats[0]->slug}<br />";
    Thread Starter Alpha Plus

    (@alpha-plus)

    I ended up working it out. I used this piece of code here:

    <?php
    	//Get campaign category name and slug
            $terms = get_the_terms( $post->ID, 'download_category' );
                if ( $terms && ! is_wp_error( $terms ) ) :
                    $categories = array();
                    $slugs = array();
                    foreach ( $terms as $term ) {
                      $categories[] = $term->name;
                      $slugs[] =  $term->slug;
                    }
                    $category = join( " / ", $categories );
                    $slug = join( " / ", $slugs );
                endif;
    ?>

    I echoed the above like this:

    <a href="/about/<? echo $slug ?>">About</a>
    <a href="/campaigns/category/<? echo $slug ?>">More from <? echo $category ?></a>

    NOTE: This will only work when the post is assigned to one category.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Finding the category slug with php’ is closed to new replies.