1

I'm trying to use get_post_meta with the following hook, but it's always empty. I adjusted the priority to see if that would help, but no luck. Any ideas?

The post meta is definitely in the db after publish.

function some_function( $new_status, $old_status, $post ) {
    if ( ( $new_status == 'publish' ) && ( $old_status != 'publish' ) && ( $post->post_type == 'cpt' ) ) {

        // send admin notification
        $post_title = get_the_title( $post->ID ); 

        $message .= 'Name: ' . $post_title . '<br>';
        $message .= 'Email: ' . get_post_meta($post->ID, '_email', true) . '<br>';

        $headers[] = 'Content-Type: text/html; charset=UTF-8';
        $headers[] = 'From: ' . get_option( 'blogname' ) . ' <' . get_option( 'admin_email' ) . '>';
        wp_mail( get_option( 'admin_email' ), $subject, $message, $headers );

    } else {
        return;
    }
}
add_action( 'transition_post_status', 'some_function', 100, 3 );

The post_title is coming across in the email using the above, just no meta data.

If there's another hook or easier way, I'm all ears!

6
  • What's the return value of get_post_meta? I see you don't check the return value for errors
    – Tom J Nowell
    Oct 22, 2019 at 22:52
  • Well, in the email that is sent get_post_meta is blank Oct 22, 2019 at 22:54
  • Then you have some debugging to do, e.g. it could be that the post meta doesn't exist, or that it does exist but it's blank, or false, or an empty string, or null, etc, etc. How are we to know if the value is never checked? Whatever it returns resolves to blank, but what exactly does it return?
    – Tom J Nowell
    Oct 22, 2019 at 23:31
  • Also how are these posts being published?
    – Tom J Nowell
    Oct 22, 2019 at 23:32
  • Tom, I'm hearing you my code SHOULD work. Is that accurate? Oct 23, 2019 at 0:10

1 Answer 1

0

I got it working by looking at this post/answer: https://wordpress.stackexchange.com/a/134283/17126

Seems it can't be done, and I changed the get_post_meta line to:

$message .= 'Email: ' . sanitize_text_field($_POST['_email']) . '<br>';

Also, I could see the $_POST data coming in from post.php on submission over dev tools.

And finally, I changed my hook to publish_cpt which you can read more about here: https://codex.wordpress.org/Post_Status_Transitions

All good now!

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.