0

I want to perform an action when a blog post gets published for the first time only. I do not want to take action on any subsequent update.

I wrote a plug-in to do this. However, it runs the function each time the post is updated, regardless of publish or update status.

Here's is a snippet of my plugin:

function emailSubscribers( $new_status, $old_status, $post ) { // 2014-04-21 http://wordpress.stackexchange.com/questions/69772/execute-function-when-post-is-published

  //error_reporting(E_ALL); ini_set('display_errors', 'On'); // don't use this -- it messes up page

  //$post = get_post($post_ID);
  //echo '<pre>'; print_r($post); echo '</pre>'; exit; // for testing purposes
  //echo '<pre>'; echo 'Published: ' . $post->post_date . '<br>' . 'Updated: ' . $post->post_modified; echo '</pre>'; exit; // for testing purposes
  $thisCategory = get_the_category($post/*->ID*/);
  $blogTitle = get_the_title($post/*->ID*/); // must be done this way so the html entities get decoded properly

  if ( 'publish' !== $new_status or 'publish' === $old_status ) return; // 2014-04-21 http://wordpress.stackexchange.com/questions/69772/execute-function-when-post-is-published
  if ( 'post' !== $post->post_type ) return; // restrict the filter to a specific post type // 2014-04-21 http://wordpress.stackexchange.com/questions/69772/execute-function-when-post-is-published

      /* the rest of my code which actually gets processed regardless of post status */

    } // end emailSubscribers()
    add_action( 'transition_post_status', 'emailSubscribers', 10, 3 );

Other answer(s) elsewhere in Stackoverflow do not solve this specific problem.

1 Answer 1

0

You can make use of dynamic hook

do_action( "{$old_status}_to_{$new_status}", $post );

in wp_transition_post_status() to target exact combination. So in your case it would be something like draft_to_publish.

I am not sure why exactly your attempt is failing though, without thoroughly debugging it.

2
  • 1
    @H.Ferrence no, add_action( 'draft_to_publish',
    – Rarst
    Commented Apr 25, 2014 at 15:42
  • 1
    @H.Ferrence add_action( 'draft_to_publish', 'emailSubscribers' ); (note less arguments passed)
    – Rarst
    Commented Apr 25, 2014 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.