2952 posts
  • 8 Years of Membership
  • Affiliate Level 5
  • Author Level 8
  • Bundle Boss
+12 more

I am learning wordpress right now and I’ve been suggested to write the code a certain way.

I trust the guy but I wanted to know what you guys think, what is better? What does user prefer?

So here’s an example :

This code :

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

Compared to this one :

<?php if (have_posts()) {
    while (have_posts()) { 

    the_post(); ?> 

Do you guys always close your php tag even if there is more PHP coming?


444 posts
  • 7 Years of Membership
  • Collector Level 1
  • Exclusive Author
  • United Kingdom

For template files I use short tags eg. if (have_posts()) : while (have_posts()) : the_post();. Its just because its more organised in some way. But in functions.php and other fully php files I use the normal php codeing

1037 posts
  • Affiliate Level 6
  • Author Level 11
  • Collector Level 4
  • Top Monthly Author
+9 more

To keep things clean with a bunch of PHP mixed in with my HTML in complicated Wordpress themes, I do all my basic if/elses and loops by line.

So in your example, I would do:

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

I don’t like seeing the PHP tags more than once in a line unless it’s mixed into some html like:

<a href="<?php the_permalink(); ?>" title="<?php the_title; ?>" />
69 posts
  • 7 Years of Membership
  • Author Level 2
  • Collector Level 1
  • Exclusive Author
+1 more

I don’t see any good reason for creating more and more php tags like the first one ;)

Bro as i know both codes are same, and they do exactly the same thing. However, I prefer to use second one as I can organize my codes well with that way, and it is easy to find any error with that code structure too. Both codes are same, only the structures are different.

374 posts
  • 8 Years of Membership
  • Affiliate Level 1
  • Author Level 3
  • Collector Level 2
+4 more

Dont close PHP tags when there’s no need to, but make sure you indent the code properly.