1

Searching the code for related posts I found two almost identical code snippets, the only difference being that one uses echo:

echo '<li><a href="' . get_permalink() . '" title="' . the_title_attribute() . '">' . the_title() . '</a></li>';

and the other does not:

<li>
<a href="<?php the_permalink() ?>" title="<?php the_title_attribute() ?>"> <h4><?php the_title() ?></h4></a>
            </li>

Personally, I understand the second version (which mixes html with php) better, but I suspect, WP being what it is (always preferring php over html), that the first version may be the official way of doing things.

Is there are any preferred way of doing things in this case? And if yes why?

6

The main differences are: the first snippet has html inside php while the second one has php inside html. Both approaches are basically valid, both are fine.

I would however always prefer (and recommend) to have php inside html because chances are that a third person / designer might have less difficulties in understanding the code and i.m.h.o. it is less likely to mess with it.

3

First one

I don't know any preferred way on this, you can use both where which demands. Though the first one you mentioned contain bugs:

echo '<li><a href="' . get_permalink() . '" title="' . the_title_attribute() . '">' . the_title() . '</a></li>';

the_title_attribute() doesn't return, but directly echo things. So when you are using it inside an echo, do it like so:

the_title_attribute( array( 'echo' => 0 ) )

similarly the_title() itself echo the whole, so when you are using it inside an echo use get_the_title() instead.

So the first one while corrected would be:

echo '<li><a href="'. get_permalink() .'" title="'. the_title_attribute( array( 'echo' => 0 ) ) .'">'. get_the_title() .'</a></li>';

Second one

Why a block element is inside an inline element?

<li>
   <a href="<?php the_permalink() ?>" title="<?php the_title_attribute() ?>">
      <h4><?php the_title() ?></h4>
   </a>
</li>

it shouldn't be that way, but something like this:

<li>
   <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
      <?php the_title(); ?>
   </a>
</li>
  • Thanks for the explanation. It proves that often the code posted on some sites as snippets or whatever, may contain bugs and should be used with care. – IXN Sep 16 '15 at 17:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.