1

In this topic our friend @toscho created a function that sets the font size according to the number of words in the post. Based on this function, I want to create a custom field whose value will be set depending on the number of words in the post. For example, if the post contains up to 200 words, automatically create custom field (add_post_meta) with value = 1; If your post contains more than 200 words, create custom field with value = 2.

Any idea is welcome. Thank you.

1 Answer 1

3

Hook into save_post, count the words, and update the post meta field.

Sample code, not tested:

add_action( 'save_post', 'wpse_73563_save_word_count', 10, 2 );

function wpse_73563_save_word_count( $post_ID, $post )
{
    if ( ! current_user_can( 'edit_' . $_POST['post_type'], $post_ID ) )
    {
        return FALSE;
    }

    $count = t5_word_count( $post->post_content );

    update_post_meta( $post_ID, '_word_count', ( 200 > $count ? 2 : 1 ) );
}
2
  • add_post_meta() will not work if the key already exists.
    – fuxia
    Commented Nov 28, 2012 at 19:06
  • Great @toscho, instead of update_post_meta() I preferred using add_post_meta(). Thanks again.
    – BobGCA2
    Commented Nov 28, 2012 at 19:12

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.