1

I have several custom post types that all share the same tags.

On the archive for each custom post type I want to display a list of tags used, and the number of posts associated with each. get_tags() by default pulls all its information from the entire site content.

I can't find any filters for the get_tags() function, and I don't want to perform and intensive queries/functions to manually count and restrict.

1
  • Looking at the source code, there's a filter called, appropriately, get_tags. Unfortunately, the docs are a little thin. Hopefully this can get you started, though.
    – Pat J
    Commented Jan 29, 2014 at 21:48

1 Answer 1

1

It should work:

global $wpdb;

// set the target relationship here
$post_type = 'post';
$taxonomy = 'tag';

$terms_ids = $wpdb->get_col( $wpdb->prepare( "
SELECT
    tt.term_id
FROM
    {$wpdb->term_relationships} tr,
    {$wpdb->term_taxonomy} tt,
    {$wpdb->posts} p
WHERE 1=1
    AND tr.object_id = p.id
    AND p.post_type = '%s'
    AND p.post_status = 'publish'
    AND tr.term_taxonomy_id = tt.term_taxonomy_id
    AND tt.taxonomy ='%s'
", $post_type, $taxonomy ) );

// here you are
$terms = get_terms( $taxonomy, array(
'include' => $terms_ids,
'orderby' => 'name',
'order' => 'ASC'
) );

It will get your tag terms for a specific custom post type. Then you can do:

foreach( $terms as $tag ) {
    echo '<li class="type-tag">' . $tag->name . '</li>'; 
}

to show your tags on a list.

3
  • If you add some information to this answer explaining what it does, and why it solves the problem, you'll get an upvote from me. Code alone does not make for a valuable answer...
    – t31os
    Commented Jan 30, 2014 at 8:38
  • @t31os - Done it.
    – Manolo
    Commented Jan 30, 2014 at 9:07
  • Sorry but unfortunately that does not clarify the answer sufficiently enough for me. For example: Why are you calling WPDB's get_col and is it required and if so, why...
    – t31os
    Commented Feb 3, 2014 at 19:26

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.