1
votes

I'm currently working on a WordPress site and I've created a custom post type called 'events' using the CPT UI plugin.

I want to display the events on my home page, so I've tried to create a loop in my homepage template in the theme files. I've been using this as a guide https://www.wpbeginner.com/wp-tutorials/how-to-create-custom-post-types-in-wordpress/

but for the life of me, I can't get the PHP that is used in that link to work for me.

<?PHP 
  $args = array( 'post_type' => 'events', 'posts_per_page' => 4 );
  $the_query = new WP_Query( $args ); 
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
  <h2><?php the_title(); ?></h2>
  <div class="entry-content">
    <?php the_content(); ?> 
  </div>
<?php wp_reset_postdata(); ?>
<?php else:  ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

When I try to save that I get this error

syntax error, unexpected 'else' (T_ELSE)

I've been searching for an answer for this for a while and I can't find anything.

I'm pretty new to PHP, so sorry if I'm being incredibly stupid. Any help would be appreciated :)

1

1 Answers

0
votes

You have not end while loop , place this code also <?php endwhile; ?>

<?php 
  $args = array( 'post_type' => 'events', 'posts_per_page' => 4 );
  $the_query = new WP_Query( $args ); 
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
  <h2><?php the_title(); ?></h2>
  <div class="entry-content">
    <?php the_content(); ?> 
  </div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else:  ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>