skip to Main Content

I have a dedicated page for every team member on my website. The title of the page is their first and last name. For every post on my site, I have two ACF ‘author’ fields. I’m trying to write a query to determine if the current team member has any posts where author_1 or author_2 contains their name.

I’m currently getting 0 posts returned even though I’m positive I should be getting some. Below is my code.

function hide_cotw_heading(){
    $title = get_the_title();
    global $post;

    $latest_posts= get_posts( array(
        'category' => 9,
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'author_1',
                'value'   => $title,
                'compare' => 'LIKE',
            ),
            array(
                'key'     => 'author_2',
                'value'   => $title,
                'compare' => 'LIKE',
            ),
        )
    ) );

      if($latest_posts){
        return 'Has posts';
      } else{
        return 'No posts';
      }
}

2

Answers


  1. I have revised your code, so please try this one

    function hide_cotw_heading() {
        $title = get_the_title();
    
        $args = array(
            'post_status'   => 'publish',
            'posts_per_page'=> -1, // Retrieve all matching posts
            'category'      => 9,
            'meta_query'    => array(
                'relation' => 'OR',
                array(
                    'key'     => 'author_1',
                    'value'   => $title,
                    'compare' => '=',
                ),
                array(
                    'key'     => 'author_2',
                    'value'   => $title,
                    'compare' => '=',
                ),
            )
        );
    
        $latest_posts = get_posts($args);
    
        if ($latest_posts) {
            return 'Has posts';
        } else {
            return 'No posts';
        }
    }
    
    Login or Signup to reply.
  2. could you give this a try?

    function hide_cotw_heading() {
        $title = get_the_title();
        $matching_posts = array();
    
        $args = array(
            'post_status'   => 'publish',
            'posts_per_page' => -1, // Retrieve all posts
            'category'      => 9,
            
        );
    
        $all_posts = get_posts($args);
    
        foreach ($all_posts as $post) {
            $author_1_data = get_field('author_1', $post->ID); // Retrieve ACF field data
            $author_2_data = get_field('author_2', $post->ID);
    
          
            if (($author_1_data && $author_1_data['label'] === $title) ||
                ($author_2_data && $author_2_data['label'] === $title)) {
                $matching_posts[] = $post;
            }
        }
    
        return count($matching_posts) > 0 ? 'Has posts' : 'No posts';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search