1

The "word_count" function below returns different values depending on where its called from. Why?

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

function myPlugin($post)
{
    global $rockScore;
    global $text;
    $text = strip_tags($post->post_content);
    echo word_count($post); //returns "350"
}

function word_count($post)
{
    global $text;
    $word_count = explode(' ', $text);
    $word_count = count($word_count);
return $word_count;
}

function my_custom_save($postID, $post){
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $postID;
    }
    else
    {
        if($parent_id = wp_is_post_revision($postID))
        {
        $postID = $parent_id;
        }
        echo word_count($post);die; //still returns "1"
    }
}

register_activation_hook(__FILE__, 'myPlugin');
2

Probably revisions. Check $post->post_type.

  • Bingo. Echo $post->post_type = "revision". What's the solution? How can I pass the original post object to the function? – Scott B Nov 1 '10 at 18:11
  • You should check the post type when using the save_post action by adding if(wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) { return $post_id; } – prettyboymp Nov 1 '10 at 18:15
  • Thanks for the help. I've revised my question with the updated code, but I'm still getting an incorrect value from the function. – Scott B Nov 1 '10 at 18:27
  • @Scott B: why don't you just pass the post_content to your word count function word_count($post->post_content); instead of using a global $text? – sorich87 Nov 1 '10 at 18:28
  • @sorich, that does work. I just figured it was too expensive to call it each time vs storing it in global. – Scott B Nov 1 '10 at 18:37

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.