noReck
noReck

Reputation: 113

Wordpress shortcode with a loop

I'm fairly new with using WP shortcodes, and I've run into a problem. I have tried to make a shortcode, that shows 6 of my blog posts through a loop, but it doesn't work. When it loads, it just smashes the page. The loop code works in practice, just not with the shortcode.

The code

function myshort() { ?>
<?php
    $args = array( 'post_type' => 'cases', 'posts_per_page' => 6 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
?>

<div class="col-sm-6 wow fadeInUp" data-wow-delay="0.1s">
    <a class="content" href="<?php echo get_permalink( $post->ID ); ?>">
        <div class="image">
            <?php the_post_thumbnail(); ?>
        </div>
        <div class="text">
            <span class="date"><?php echo rwmb_meta( 'rw_stitle' ); ?></span>
            <h3><?php the_title(); ?></h3>
            <p><?php echo rwmb_meta( 'rw_sdesc' ); ?></p>
        </div>
    </a>
</div>

<?php endwhile;
}

add_shortcode('doitman', 'myshort');

So, my question is, how do I write this the right way?

Upvotes: 0

Views: 3869

Answers (1)

Amin Abdolrezapoor
Amin Abdolrezapoor

Reputation: 1847

The result should be returned as a value, you could try something like this :

function myshort() {
    ob_start(); ?>
<?php
    $args = array( 'post_type' => 'cases', 'posts_per_page' => 6 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
?>

<div class="col-sm-6 wow fadeInUp" data-wow-delay="0.1s">
    <a class="content" href="<?php echo get_permalink( $post->ID ); ?>">
        <div class="image">
            <?php the_post_thumbnail(); ?>
        </div>
        <div class="text">
            <span class="date"><?php echo rwmb_meta( 'rw_stitle' ); ?></span>
            <h3><?php the_title(); ?></h3>
            <p><?php echo rwmb_meta( 'rw_sdesc' ); ?></p>
        </div>
    </a>
</div>

<?php endwhile;

    return ob_get_clean();
}

add_shortcode('doitman', 'myshort');

Upvotes: 1

Related Questions