Support

Account

Home Forums ACF PRO Comparing two select fields

Solved

Comparing two select fields

  • I have created the following:

    1. A repeater field on an options page to register customers.
    2. A select field in a custom post type that is dynamically being filled from the repeater field in #1.
    3. A select field in WordPress user form that is dynamically being filled from the repeater field in #1.

    What i want is to send the appropriate users an email each time a custom post type is posted, which has the same customer selected as the user. As an example;

    If a custom post type is posted with “Customer A” in the select field, i want a mail to be sent to all users having “Customer A” set in the select field in in their WordPress user.

    This is my code so far:

    function on_post_publish( $ID, $post ) {
    
      //Getting value of select field in published post
      $kunde = get_field('kunde', $post->ID);
    
      //Fetching all user data
      $users = get_users();
    
      foreach ( $users as $user ) {
    
        $userID = 'user_'. $user->ID; //also tried with $ID, but with the same result
    
        $kunde2 = get_field('velg_kunde', $userID);
    
        if ( $kunde == $kunde2 ) {
          $to = $user->user_email;
          $subject = 'Email topic';
          $message = 'Email message';
    
          wp_mail( $to, $subject, $message );
        }
    
      }
    
    }
    add_action(  'publish_jobb',  'on_post_publish', 10, 2 );

    I’m suspecting there’s something wrong with how I get the select fields, although I’ve tried with get_field_object also – with with no luck. What I’m also suspecting is that there might be something off with my conditional $kunde == $kunde2, but I haven’t been able to figure out just what.

    Any ideas would be helpful. Right now all that happens when I register a custom post type with any given customer selected, a mail is sent to the only user that has no customer selected; the site admin.

  • Figured it out. The publish-hook is to early for ACF, so none of the newly published fields are ready yet. I changed it up to this:

    add_action( 'save_post', 'save_jobb', 100, 3 );

    ..also cranking up the priority to 100, to make sure that all other save jobs are done first.

    Furthermore I added a check for post type early in the new function, since the new one takes on all posting in general:

    $post_type = get_post_type($post_id);
    if ( "jobb" != $post_type ) return;

    Lastly, to prevent emails from being sent every time I edit a post belonging to a customer, I also added a small, new ACF field named mailsendt – to just hold the value 0 or 1 depending on whether a mail already has been sent or not.

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

The topic ‘Comparing two select fields’ is closed to new replies.