Support

Account

Home Forums General Issues ACF field true/false

Solved

ACF field true/false

  • Hello,

    I created a true / false type “notify by email” custom field in ACF. I would like that when the toggle is on “true” it sends the administrators an e-mail indicating “New post published on the site. Find it here: …..”.

    For the notification e-mail, it works fine unconditionally, so send notification systematically after publishing a new post. On the other hand, when I try to add if (get_field (‘my-custom-field’)); to my code this does not work. It doesn’t matter if the field is active or not it does not send an email.

    Here is my code:

    add_action( 'publish_post', 'send_notification' );
    function send_notification( $post_id ) {
    	if(get_field('my-custom-field')) {
    
            $args = array (
                'role' => 'administrator',
    			'role' => 'subscriber'
            );
    
            $user_query = new WP_User_Query( $args );
    
             $email_addresses = array();
            foreach ( $user_query->results as $user ) {
                $email_addresses[] = $user->user_email;
            }
    
            $post_title = get_the_title( $post_id ); 
            $post_url = get_permalink( $post_id ); 
            $subject = "New post published";
    		$message = "Hello,\n";
            $message .= "The post has just been published :" . $post_url . "\n\n";
    	    $message .= "Thank you.";
    
            wp_mail($email_addresses, $subject, $message );
    	}
    }

    Can you help me please ?

    Thank you so much!

  • The problem is that ‘publish_post’ happens before save_post and ACF saves values on the latter. This means that you are attempting to get a value that ACF has not yet set.

    You either need to use the acf/save_post hook with a priority > 10 or you need to look for the value in $_POST[‘acf’]

    https://www.advancedcustomfields.com/resources/acf-save_post/

  • It works perfectly, thank you very much John Huebner!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.