Reputation: 1075
as the title said, I'm trying to write a custom WordPress filter which limits the creation of Tag pages so that Tag pages are only created if the Tag has more than 10 associated posts. This is because we have so many tags with <10 associated posts, and it's creating a lot of noise.
I've not worked with WordPress for almost 5 years now, so I'm a bit rusty.
Here's what I'm trying, and it's not quite working:
<?php
function limit_taxonomies_by_count( $args, $taxonomy, $object_type ) {
$terms = get_terms('post_tag');
foreach($term in $terms) {
if ($term->count < 10) {
$args = array(
'public' => false
)
}
}
return $args
}
add_filter('register_taxonomy_args', 'limit_taxonomies_by_count' );
?>
Please let me know what I'm missing!
Upvotes: 1
Views: 472
Reputation: 3958
Instead of preventing the admins / editors from adding new tags, you could just "hide" Tag archive pages that don't meet the criteria (10 or more posts assigned to them). This way, admins/editors can still create / use new tags that might eventually reach 10 or more posts which will then make them visible to visitors.
To do so, you can use the template_redirect action hook to do something before the Tag archive page is loaded on screen (that something is explained next), then the is_tag() function to check whether the visitor is trying to access a Tag archive page, and finally the wp_redirect() function to do the actual redirection:
/**
* Redirects visitors to the homepage for Tags with
* less than 10 posts associated to them.
*/
function wp76515_tag_maybe_redirect(){
// We're viewing a Tag archive page
if ( is_tag() ) {
// Get Tag object
$tag = get_tag(get_queried_object_id());
// Tag's post count
$post_count = $tag->count;
// This tag has less than 10 posts,
// redirect visitor
if ( $post_count < 10 ) {
wp_redirect(
home_url(), // The URL we're sending the visitor to
'302' // The HTTP status, 302 = 'Moved Temporarily'
);
}
}
}
add_action('template_redirect', 'wp76515_tag_maybe_redirect', 5);
You may want to change the redirect code to 301
(Moved Permanently) to remove existing Tag pages with less than 10 posts from Google's index as well.
Upvotes: 1
Reputation: 2770
You can do as follows to achieve your job done. You can remove those tags link whose associated posts count are less than 10, so visitors can never click on those tags.
function modify_term_link_url( $links ) {
global $post;
if( !$post ) return $links;
$terms = get_the_terms( $post->ID, 'post_tag' );
if ( is_wp_error( $terms ) ) {
return $terms;
}
if ( empty( $terms ) ) {
return false;
}
$links = array();
foreach ( $terms as $term ) {
if( $term->count < 10 ){
$link = '';
}else{
$link = get_term_link( $term, 'post_tag' );
if ( is_wp_error( $link ) ) {
return $link;
}
}
$links[] = '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
return $links;
}
add_filter( 'term_links-post_tag', 'modify_term_link_url' );
Codes goes to your active theme's functions.php
Upvotes: 1