PHP code within echo

Hi, can anyone help me solve the following problem?

I’m trying to create a widget within WordPress using the following PHP code:


<?php
class Engine_Latest_Posts_Widget extends WP_Widget {
    function  __construct() {
        parent::__construct('engine-latest-posts-widget', 'Engine Latest Posts Widget');
    }
    function widget($args, $instance) {
        echo '
		<li class="widget-container" id="widget-latest-posts">
			<div class="widget-header"><h3>Latest Blog Posts</h3></div>
			<div class="widget-content">
				<div class="coda-slider-wrapper">
                    <div class="coda-slider preload" id="coda-slider-5">
						HELLO
						<?php query_posts("cat=4&showposts=5"); ?>
						<?php while (have_posts()) : the_post(); ?>
						
						<div class="coda-panel">
							<div class="coda-panel-content">
								<h6><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h6>
							</div>
						</div>
						
						<?php endwhile;?>

                    </div><!-- .coda-slider -->
                </div><!-- .coda-slider-wrapper -->
			</div>
		</li>';
    }
    function form($instance)
    {
    }
}
register_widget('Engine_Latest_Posts_Widget');
?>

I suspect that the problem is caused because I’m attempting to use code like “<?php query_posts(“cat=4&showposts=5”); ?>” within an “echo”, which is just printing this in the source code, rather than actioning it as PHP code.

But… I don’t really know PHP and I don’t know how to fix it. I’ve attempted to learn what I need to know via several tutorials, but nothing I have tried has worked.

Any suggestions? Thank you! :slight_smile:

By using PHP heredoc, we can print the php code…
Follow this;
PHP heredoc syntax

Essentially the best thing to do is use an echo statement for every line then call the PHP you need to run. See the updated code below…

<?php

function widget($args, $instance) {
    echo '<li class="widget-container" id="widget-latest-posts">';
    echo '    <div class="widget-header"><h3>Latest Blog Posts</h3></div>';
    echo '    <div class="widget-content">';
    echo '        <div class="coda-slider-wrapper">';
    echo '            <div class="coda-slider preload" id="coda-slider-5">';
    echo '                HELLO';
    
    query_posts("cat=4&showposts=5");
    while (have_posts()): the_post();
    ?>
        <div class="coda-panel">
            <div class="coda-panel-content">
                <h6><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h6>
            </div>
        </div> 
    <?php
    endwhile;
    
    echo '            </div><!-- .coda-slider -->';
    echo '        </div><!-- .coda-slider-wrapper -->';
    echo '    </div>';
    echo '</li>';
}

I love these forums! :smiley:

Thank you - that works perfectly!

…and extra thanks for making my life that little bit easier after only 15 minutes of me posting!