Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress Shortcode with ob_start()
function custom_query_shortcode($atts) {
// EXAMPLE USAGE:
// [loop the_query="showposts=100&post_type=page&post_parent=453"]
// Defaults
extract(shortcode_atts(array(
"the_query" => ''
), $atts));
// de-funkify query
$the_query = preg_replace('~&#x0*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $the_query);
$the_query = preg_replace('~&#0*([0-9]+);~e', 'chr(\\1)', $the_query);
// query is made
$q = new WP_Query($the_query);
if($q->have_posts()) :
ob_start();
?>
<div class="row news-v1">
<!-- loop start -->
<?php while ($q->have_posts()): $q->the_post(); ?>
<div class="col-md-4 md-margin-bottom-40">
<div class="news-v1-in">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'medium', array( 'class' => 'img-responsive' ) );
}
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p><?php echo custom_excerpts($post->ID, 25); ?></p>
<ul class="list-inline news-v1-info">
<li><span>By </span><?php the_author_posts_link(); ?></li>
<li>|</li>
<li><i class="fa fa-clock-o"></i> <?php the_time('M d, Y'); ?></li>
<li class="pull-right"><a href="<?php the_permalink(); ?>"><?php comments_number( '<i class="fa fa-comments-o"></i> 0 comment', '<i class="fa fa-comments-o"></i> 1 Comment', '<i class="fa fa-comments-o"></i> % comments' ); ?></a></li>
</ul>
</div>
</div>
<?php endwhile; ?>
<!-- loop end -->
</div>
<?php else : ?>
<p> Nothing found! </p>
<?php endif; ?>
<?php
$output_string = ob_get_contents();
ob_end_clean();
return $output_string;
wp_reset_postdata();
}
add_shortcode('loop', 'custom_query_shortcode');
?>
@linusrud

This comment has been minimized.

Copy link

commented Aug 30, 2017

I'm pretty sure that wp_reset_postdata(); after the return statement will never run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.