I was working on creating my first plugin/widget that should display a really simple loop containing only a custom field (image)

I've been testing the loop without any problems in my theme but when I place the loop in my plugin file it generates a fatal error preventing the plugin to b activated. I really don't understand why this happens as the loop works without any problems in the theme.

This is the loop that I'm using:

<?php $args = array(
    'posts_per_page' => 3,
    'post_type' => 'sponsors',
    'orderby' => 'rand',
$the_query = new WP_Query( $args ); ?>

<?php if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post();  ?>
$image = get_field('sponsor');
if( !empty($image) ): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php endif; ?>
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>

And this is the fatal error displayed when activating the plugin:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

I've already solved it another way by using the PHP Code Widget plugin but would like to know why I get this error. If I need to place the full plugin code let me know.

1 Answer 1


UPDATE: Okay, Looking at the Error, it should be easy. Just remove any Whitespaces or Clear Lines at the end of your Plugin file after the last "?>".


Did you copy&paste the code here? Because it seems like you have some whitespaces that should not be there in the line

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

If you remove the whitespaces (like this:

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

), it should work.

P.S.: Don't forget to use

<?php wp_reset_postdata(); ?>

after the

<?php endwhile; ?>

Otherwise it could end up messing with the rest of your page ^^

Happy Coding, Kuchenundkakao

  • No, the whitespaces are because of copy/pasting, it's fine in the plugin file. According to the shown error there's an error in the <img src=".... line.
    – NielsPilon
    Jul 15, 2014 at 11:58
  • Updated the answer... Jul 15, 2014 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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