This question is sort of a follow up from another question on here Order posts by tags count?

The first comment recommends counting the number of tags and saving it into a custom meta field. Going from that, I've put this in my single.php

$terms = get_the_terms( $post->ID, 'taxonomy' );
$terms_count = count ( $terms );
if ( ! add_post_meta($post->ID, 'custom-field-name', $terms_count, true ) ) { 
        update_post_meta( $post->ID, 'custom-field-name', $terms_count );

This first question is - is this code alright? It seems to work fine, but I basically just copied it over from the Wordpress codex.

The second question - is there a way to trigger this function when I update the post, instead of it being updated every time the page is reloaded? Seems redundant this way.

  • 1
    See save_post. – Sally CJ Jul 20 '19 at 8:27
  • 1
    Yup, that solved it. Thanks! @SallyCJ – Dan Jul 20 '19 at 8:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.