badcoder
badcoder

Reputation: 3834

Wordpress get_post_meta() not working in functions.php

I have a custom post type called 'work' in WP and need an email sent to an administrator every time a custom field 'socialmedia' has the value of 'yes'. The following code sends the mail fine but does not include the custom field value in the email:

function email_members($post_ID)  {
global $post;
if ( 'work' == get_post_type($post_ID) ){
    $social = get_post_meta($post_ID, 'socialmedia', true);
    mail('[email protected]', get_the_title($post_ID), $social);
}
return $post_ID;
}

add_action('publish_work', 'email_members');

Any ideas?

Thanks

Upvotes: 0

Views: 3231

Answers (3)

Tom
Tom

Reputation: 1366

Check the meta value before you send the email.

if( 'yes' == ($social = get_post_meta($post_ID, 'socialmedia', true)) )
{
  mail('[email protected]', get_the_title($post_ID), $social);
}

Upvotes: 1

David Gard
David Gard

Reputation: 12047

Get rid of global $post (doesn't appear to be used), and add some var_dump(); lines to show you exactly what your variables contain, helping you to pin point the error.

Also, you mention that you want to send an email on if socialmedia is 'yes', but you have no check for that in your code?

function email_members($post_ID)  {

    var_dump($post_ID);
    var_dump(get_post_type($post_ID));

    if ( 'work' == get_post_type($post_ID) ){

        $social = get_post_meta($post_ID, 'socialmedia', true);
        var_dump($social);

        if ( $social === 'yes' ) {
            mail('[email protected]', get_the_title($post_ID), $social);
        }

    }

    die(); // Remove this after testing, it'll stop WP redirecting you so you can see what your variables contain.

    return $post_ID;
}

add_action('publish_work', 'email_members');

Upvotes: 1

Chris Gastrell
Chris Gastrell

Reputation: 21

If you already pass $post_ID via function, what's the point of the global? How about ...

if(get_post_type($post_ID) === "work"){ 
    // do stuff 
}

Make sure it indeed returns "work" with ...

var_dump(get_post_type($post_ID);

Also, unless we know where you use the function. E.g in the loop, out of the loop? We can't really help much or well, I can't really help much.

Upvotes: 0

Related Questions