Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
WordPress Shortcode with ob_start()
function custom_query_shortcode($atts) {
// [loop the_query="showposts=100&post_type=page&post_parent=453"]
// Defaults
"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()) :
<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">
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><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>
<?php endwhile; ?>
<!-- loop end -->
<?php else : ?>
<p> Nothing found! </p>
<?php endif; ?>
$output_string = ob_get_contents();
return $output_string;
add_shortcode('loop', 'custom_query_shortcode');

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.