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.

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
    Nov 28 '12 at 19:06
  • Great @toscho, instead of update_post_meta() I preferred using add_post_meta(). Thanks again.
    – BobGCA
    Nov 28 '12 at 19:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.