Skip to content

Instantly share code, notes, and snippets.

@ara303
Created September 13, 2024 16:52
Show Gist options
  • Save ara303/edd3cc712de9745b8dc3638faa163ee9 to your computer and use it in GitHub Desktop.
Save ara303/edd3cc712de9745b8dc3638faa163ee9 to your computer and use it in GitHub Desktop.
Get a list of all of the tags used on a custom post type of a certain category
<?php
/*
* Assumes your custom post type is called `sma_members`, and that your category has ID `70`.
* You'd want to chage this if you reused these.
*/
function get_cached_sma_members_tags() {
$cached_tags = get_transient('sma_members_category_70_tags');
if (false !== $cached_tags) {
return $cached_tags;
}
$tags = fetch_sma_members_tags();
set_transient('sma_members_category_70_tags', $tags, 0);
return $tags;
}
function fetch_sma_members_tags() {
$args = array(
'post_type' => 'sma_members',
'cat' => 70,
'posts_per_page' => -1,
);
$query = new WP_Query($args);
$tag_ids = array();
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post_tags = wp_get_post_tags(get_the_ID());
foreach ($post_tags as $tag) {
$tag_ids[] = $tag->term_id;
}
}
}
wp_reset_postdata();
$unique_tag_ids = array_unique($tag_ids);
return get_tags(array(
'include' => $unique_tag_ids,
'hide_empty' => false,
));
}
// This handles flushing the WP Transients cache whenever a post of the type is updated (better than a TTL expiration)
function refresh_sma_members_tags_cache($post_id) {
if( get_post_type($post_id) === 'sma_members' ){
$tags = fetch_sma_members_tags();
set_transient( 'sma_members_category_70_tags', $tags, 0 );
}
}
add_action('save_post_sma_members', 'refresh_sma_members_tags_cache');
add_action('deleted_post', 'refresh_sma_members_tags_cache');
add_action('edited_terms', 'refresh_sma_members_tags_cache');
add_action('delete_term', 'refresh_sma_members_tags_cache');
// Usage
$tags = get_cached_sma_members_tags();
if (!empty($tags)) {
echo '<ul>';
foreach ($tags as $tag) {
echo '<li>' . $tag->name . '</li>';
}
echo '</ul>';
} else {
echo 'No tags found.';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment