Home > other >  WP_Query is not working on the custom pages
WP_Query is not working on the custom pages

Time:06-13

I'm trying to output Team Members on the page. I have created two custom post types "team-member" and "occupation" and assigned ACF fields to them, so each team member have a occupation associated using relationship option at ACF. All works ok, until I try to output the Team Members on the page for example page-services.php. The Query works on single-occupation.php with no problems which is my single post template, showing the correct team member for particular occupation, but is not working on other custom pages like mentioned page-services.php

My Query:

<?php
    $relatedTeamMembers = new WP_Query(array(
        'posts_per_page' => -1,
        'post_type' => 'team-member',
        'orderby' => 'title',
        'order' => 'ASC',
        'meta_query' => array(
        array(
            'key' => 'related_occupation',
            'compare' => 'LIKE',
            'value' => '"' . get_the_ID() . '"'
        )
        )
    ));

    if ($relatedTeamMembers->have_posts()) {

        echo '<ul>';
            while($relatedTeamMembers->have_posts()) {
                $relatedTeamMembers->the_post(); ?>
                    <li>
                        <a href="<?php the_permalink(); ?>">
                            <img src="<?php the_post_thumbnail_url(); ?>">
                            <span><?php the_title(); ?></span>
                        </a>
                    </li>
            <?php }
        echo '</ul>';
    }
    wp_reset_postdata();
?>

I don't have any errors just nothing outputted on the page. I have also used wp_reset_postdata() function even if I do not run multiple queries on the same page, but this doesn't help. I would be super grateful if someone could help me to understand what I'm doing wrong here...

CodePudding user response:

When you are not in the single page of the post type, there is no refernce to a single post using get_the_ID().

On your custom page, you have not defined what the id should be. So the query has no match with the value you are looking for in your meta_query.

If you want to output a specific occupation, you will have to set an id. Assung the id of your occupation (you see it in the url on mouse over in the backend) is '1049', your code could look like:

'meta_query' => array(
        array(
            'key' => 'related_occupation',
            'compare' => 'LIKE',
            'value' => '1049' // id of occupation
            )
        )
  • Related