Display custom field of specific post where post title matches variable

I have a custom post type called vacancies and another called our_homes

How do I get the google map coordinates from our_homes and display inside the vacancies single post template?

My attempt below shows my tragic attempt at code inside the single-vacancies.php file:

 <?php 
    //Query custom post type our_homes and display tabs for each
    $query = new WP_Query( array( 'post_type' => 'our_homes', 'field' => 'slug', 'posts_per_page' => 999 ) ); 

    if ( $query->have_posts() ) : 

    //$count = 1;
    //$title = the_title();
    //$location = get_field('google_map_coordinates');

    ?>
    <?php while ( $query->have_posts() ) : $query->the_post(); 
        $location = get_field('google_map_coordinates', post_title);
    ?>  
    <?php if($title = $label) { echo $title; }

        //echo $label;


     ?>

    <?php endwhile; wp_reset_postdata(); ?>

<?php endif; ?>

2 Answers
2

Although your question is confusing, but based on your attempts, I can say that you are using a loop inside another loop. You should store an array of main loop’s titles in an array, and then write another loop outside the original loop and check the array.

So, this is what your main query would look like (I summarized it and removed the actual loop):

if(have_posts()){
    // Define an empty array
    $posts_title = array();
    while(have_posts()){
        // Store each title inside the array
        $posts_title[] = get_the_title();
    }
}

Now, you have an array of post titles. Write this query after the main query is finished, and closed:

$query = new WP_Query( 
    array( 
        'post_type' => 'our_homes',
        'posts_per_page' => -1 
    ) 
); 
if ( $query->have_posts() ) { 
$count = 0;
    while ( $query->have_posts() ) { 
    $query->the_post(); 
        $count++;
        // Check if this post's title matches the $label
        if( in_array( get_the_title(), $posts_title )) {
            // Do whatever you want
            the_title();
        }
    }
}
wp_reset_postdata();

Also, if you need to get the post’s or page’s ID by their title, you can use get_page_by_title('TITLE HERE') function.

Leave a Comment