I made this action hook which will send an email to the users every time a new post in the custom post type “events” is made.
function email_members($post_id) {
global $wpdb;
$usersarray = $wpdb->get_col("SELECT user_email FROM wp_users");
$users = implode(",", $usersarray);
if( ( $_POST['post_status'] == 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) ) {
$subject = 'Event Reminder';
$post_url = get_permalink($post_id);
$post_title = get_the_title($post_id);
$event_date = get_post_meta( $post_id, 'ch_event_date', true );
$message = "APAC Ministries Event Reminder for: ".$post_title."nn";
$message .= "Date: ".$event_date;
wp_mail($users, $subject, $message );
}
}
add_action('publish_th_events', 'email_members');
However, the $event_date
is always empty. I tried running this code in a different file and it works:
global $post;
$test = get_post_meta($post->ID, 'ch_event_date', true);
echo $test;
I have also tried using global $post;
and using $post->ID
as the ID. I have also tried getting the terms, and it displays fine. I’m just having trouble displaying the meta.
Any alternative solutions are welcome. Thanks!
get_post_meta
as seen here is nothing more than a wrapper forget_metadata
. Now when you say the meta you’re getting back, if its not null but rather an empty string, it means you’re hitting the end ofget_metadata
as seen here. With true defined as the third variable of your get_post_meta call, you should be seeing an empty string if this is the case. If you change it to false, you should see an empty array.Now to the issue of why you’re at the bottom of get_metadata.
Based on what I can see, the only way to get there is that you don’t actually have a post_meta_field called “ch_event_date” defined for that post_object.
Perhaps, try doing this right above your call to get “ch_event_date” as a test:
update_post_meta($post_id,'ch_event_date', 'Chris figured it out');
Then dump that get_post_meta call.
Okay, so I just tried it out on a site I’m developing and using something similar to below, I was able to do what you’re having trouble doing, using a custom field.
The only reasoning that makes any sense to me is using the
get_the_...
is only returning the values for future use, not for displaying them. In the Codex it appears that the function automatically prints or echoes the$users
and$subject
If you look closely at your test where it displays the date properly, you
echo
it. I hope this helps!