Search code examples
phpwordpressmetadatacustom-post-typewordpress-hook

Wordpress hook for newly published post that can access to post metadata


I need to do some actions only on newly published posts that requires post metadata.

I've tried many different hooks, but they all also trigger for other "events" like updating post, or if they trigger only on publish, metadata is empty or just has _edit_lock value inside.

  1. auto-draft_to_publish hook triggers when I need it, but there is no post meta

add_action(
  'auto-draft_to_publish',
  'wpse120996_specific_post_status_transition'
);

function wpse120996_specific_post_status_transition($post) {
  if ($post->post_type != 'poruke') {
    return;
  }

  $post_meta = get_post_meta($post->ID);
  echo "<pre>";
  die(var_dump( $get_post_meta ));
  echo "</pre>";
}
  1. transition_post_status works with the right status checks, but there is no post meta as well
'publish' === $new_status && 'publish' !== $old_status
// right time,no post meta
  1. publish_post it seems that this one doesn't even trigger for some reason
add_action( 'publish_post', 'myfunction' );
function myfunction($post) {
  echo "<pre>";
  die(var_dump( 'PUBLISHED?' ));
  // this dump is nowhere to be found,
  // I looked in network tab in debugger
  echo "</pre>";
}
  1. save_post this one triggers as soon as "Add New" is pressed in a sidebar

I'm having a lot of problem with this and I have hard time believing that something so "basic" would not be a feature in WordPress, but I didn't find anything helpful in my search so far.

Thanks in advance.


Solution

  • I ended up using the publish_post hook, originally It wasnt working because if you have custom post type it has to be used like this:

     publish_yourCustomPostName
    

    It still didn't have access to post meta from database because it's triggered before postmeta is saved to the database, but luckily I could access post meta from $_POST variable like this:

    $_POST['acf']