Created
March 3, 2016 03:16
-
-
Save azizultex/aee81cc0f7f6253f9362 to your computer and use it in GitHub Desktop.
WordPress Shortcode with ob_start()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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('~�*([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $the_query); | |
$the_query = preg_replace('~�*([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'); | |
?> |
Also you should not close the PHP tags to prevent problems from echoing characters after it.
Do not end in ?>, it is not necessary.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm pretty sure that
wp_reset_postdata();
after the return statement will never run.