Support

Account

Home Forums General Issues Count relationships

Helping

Count relationships

  • Hi,

    I’ve created the following function in order to return the number of posts attached (via relationship field) to a custom post type :

    function acf_save_post_nombre_avis ($post_id) {
    
    $nombre_avis = count(get_field('avis_clients'));
    
    update_field('nombre_avis', $nombre_avis, $post_id);
    
    }
    
    add_action('acf/save_post', 'acf_save_post_nombre_avis', 20);

    It works well, except when there are no post attached, the function returns 1 instead of 0….

    Any idea of what I am doing wrong ?

    Thanks !

  • 2 issues

    1) you need to supply the post ID for both getting and setting a field.

    2) count may be giving an error if no value is being returned

    
    function acf_save_post_nombre_avis ($post_id) {
      $nombre_avis = 0;
      $avis_clients= get_field('avis_clients', $post_id);
      if (!empty($avis_clients)) {
        $nombre_avis = count($avis);
      }
      update_field('nombre_avis', $nombre_avis, $post_id);
    }
    
    add_action('acf/save_post', 'acf_save_post_nombre_avis', 20);
    
Viewing 2 posts - 1 through 2 (of 2 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.