0

I'm trying to send an email to all users who are following a certain post author when they publish a post. I have this function below, but does not seem to work. a few notes

the meta value = 'following' is an array that contains the authors user follows.

function followerPost_notification($post_id) {

$post = get_post($post_id);
$uid = $post->post_author;
$user_info = get_userdata($post->post_author);
$email = $user_info->user_email;
$first_name = $user_info->first_name;
$pTitle = $post->post_title;
$pUrl = get_permalink($post_id);

//Email Info
$subject = 'New Post Published by a Person you Follow!' ;
$headers[] = 'Content-Type: text/html; charset=UTF-8';

// WP_User_Query arguments
$args = array (
    'meta_query
    '     => array(
        array(
            'key'   => 'following',

        ),
    ),
);

// The User Query
$user_query = new WP_User_Query( $args );

$q = $user_query->results;
// The User Loop
if ( ! empty( $user_query->results ) ) {
    foreach ( $user_query->results as $user ) {
        $uid2 = $user->ID;
        $uemail = $user->user_email;
        $to = $uemail;
        $meta= get_user_meta($uid2,'following', true);
        $arr = implode(',', $meta);

    if(strpos($uid, $arr)) {

    ob_start(); 

include("template/email_header.php");
?>
<p>New post published by a person you follow</p>

<p><em>This is an automated email, please don't reply to this email.</em></p>
<?php 
include("template/email_footer.php");

    $message = ob_get_contents();
ob_end_clean();

wp_mail( $to, $subject, $message, $headers );

    }

    }
} else {
    // no users found
}

}
add_action('publish_post', 'followerPost_notification');
1

Was able to figure out that the meta value was being stored as a string, which doesn't play nice with the meta query.

So what I had to do was do a like comparison with the serialized string version of my meta value. The meta query ended up like this

$args = array (
    'meta_query'     => array(
        array(
            'key'   => 'following',
            'value'   => serialize( strval( $uid ) ),
            'compare'   => 'LIKE',

        )
    )
);

for more insght, check out this other post that helped me

How can I create a meta_query with an array as meta_field?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.