javascriptphpwordpress

WordPress - Display page content and not custom post type with <?php the_content();?>


I have created a custom post-type with a single page that serves as a template page, the CPT are listed as expected but when I include the to list display the page content, it displays for a post content instead

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

      $args = array(
            'posts_per_page' => -1,
            'post_type' => 'rooms',
        );

        $the_query = new WP_Query($args);
        $categories_posts = array();

        if ($the_query->have_posts()) :
            while ($the_query->have_posts()) : $the_query->the_post();
          //code
          <? endwhile; endif; ?>

           <?php the_content();?>

I tried to move the <?php the_content();?> above the query and it displays the content i need but it doesn't work below the query


Solution

  • If <?php the_content(); ?> must be placed below the custom query, you need to reset the main query after your custom loop by adding wp_reset_postdata(); right after endwhile; endif;. This will allow <?php the_content(); ?> to display the page content instead of the custom post type content.

    Here's the updated code snippet:

    <?php while ( have_posts() ) : the_post(); ?>
    
    <?php 
      $args = array(
        'posts_per_page' => -1,
        'post_type' => 'rooms',
    );
    $the_query = new WP_Query($args);
    $categories_posts = array();
    
    if ($the_query->have_posts()) :
      while ($the_query->have_posts()) : $the_query->the_post();
        // Code for custom post type content
      endwhile; 
      endif; 
      wp_reset_postdata(); // Reset after custom query
    ?>
    
    <?php the_content(); ?> <!-- Displays the page content -->
    
    <?php endwhile; ?>