WP: Custom fields showing up, but causing errors throughout the site (get_posts)

I seem to be having a problem. When I add this bunch of code, the custom fields show up just fine, but everything around the site is in chaos! All of my page titles resort to the same one and the the_content disappears. I’m sure I’m missing something here:

<?php
$posts = get_posts(array(
    'numberposts' => -1,
    'post_type' => 'page',
    'meta_query' => array(
        array(
            'key' => 'project_categories',
            'value' => '"boyle_upcoming"',
            'compare' => 'LIKE'
        )
    ),
    'order' => 'ASC'
));

if($posts) {
    foreach($posts as $post) {
        echo '<li><a href="' . get_permalink($post->ID) . '">' . '<img src="' . get_field('project_header_photo') . '" alt="' . get_the_title($post->ID) . '">' . '<div><em><b>' . get_the_title($post->ID) . '</b><br>' .get_field('project_location') . '<br><br>' . get_field('project_blurb') . '</em></div></a></li>';
    };
}
wp_reset_query();   

?>

Read More

I thought… maybe I had to add the usual loop before and then close it after:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

…but that didn’t work. What am I missing?

Related posts

Leave a Reply

1 comment

  1. Including the code for you. this work and will not mess up your $post.

     <?php
             $args = array(
                'post_type'       => 'page',
                'post_status'     => 'publish',
               'posts_per_page'  =>  -1,
               'order'           => 'ASC',
               'meta_query' => array(
                       array(
                           'key' => 'project_categories',
                           'value' => 'boyle_upcoming',
                           'compare' => 'LIKE'
                       )
                   ),
             );
             // The Query
             $the_query = new WP_Query( $args );
    
             // The Loop
             if ( $the_query->have_posts() ) {
    
                while ( $the_query->have_posts() ) {
                    $the_query->the_post();
                     echo '<li><a href="' . get_permalink($the_query->post->ID) . '">' . '<img src="' . get_field('project_header_photo') . '" alt="' . get_the_title($the_query->post->ID) . '">' . '<div><em><b>' . get_the_title($the_query->post->ID) . '</b><br>' .get_field('project_location') . '<br><br>' . get_field('project_blurb') . '</em></div></a></li>';
    
    
             } else {
                echo "No DATA";
             }
             /* Restore original Post Data */
             wp_reset_postdata();
             ?>