I think the best option would be is to use your getPostViews()
count and incorporate a system in there to append the trending
term to the post once your counter hits 150.
Here is our worksflow
-
Get the post view count (which you are already doing)
-
Compare the current count to the desired 150
-
Use
wp_set_object_terms()
to append thetrending
term to the post
IN CODE
(I have modified your code slightly. Also note, the code is untested)
function getPostViews()
{
// Check if we are on a single page, bail out if not
if ( !is_single() )
return false;
// Get the current post id
$current_post_id = get_queried_object_id();
$count_key = 'post_views_count';
$count = get_post_meta( $current_post_id, $count_key, true );
// Set up our function to set our term 'trending'
if ( $count >= 150 ) {
/**
* First check if the term is not yet set, if not, set the term
* I have used trending as term slug. Change as needed
* Also, add the correct taxonomy to which trending term belongs to
*
* @link https://codex.wordpress.org/Function_Reference/has_term
*/
if ( !has_term( 'trending', 'MY_TAX', $current_post_id ) ) {
/**
* Append the term trending to the post
*
* @link https://codex.wordpress.org/Function_Reference/wp_set_object_terms
*/
wp_set_object_terms(
$current_post_id, // Current post ID
'trending', // Slug of term to append
'MY_TAX', // Taxonomy that the term trending belongs to
true // VERY VERY IMPORTANT, Append the term to the other existing terms
);
}
}
if( !$count ){
delete_post_meta( $current_post_id, $count_key );
add_post_meta( $current_post_id, $count_key, '0' );
}
$views = ( $count ) ? $count . ' Views' : '0 View';
return $views;
}
You can just simply use the code in your single page as follow
echo getPostViews();
and the function does the rest