Created
March 18, 2013 16:50
-
-
Save gicolek/5188718 to your computer and use it in GitHub Desktop.
Output Control WP Shortcode
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
<?php | |
add_shortcode( 'list-posts', 'smoney_list_posts' ); | |
function smoney_list_posts($atts, $content = null) { | |
extract( shortcode_atts( array( | |
'numb' => 5, | |
), $atts ) ); | |
if ( !is_page() ) { | |
$out = 'This shortcode can only be used on a page'; | |
return $out; | |
} | |
$cats = get_the_category(); | |
$query_cats = array( ); | |
// fire output buffering to write cleaner code | |
ob_start(); | |
// construct the query parameter for each category the page belongs to | |
foreach ( $cats as $cat ) { | |
$query_cats[] = $cat->term_id; | |
} | |
$args = array( | |
'category__in' => $query_cats, | |
); | |
// run the query given the parameters | |
$related_posts = new WP_Query( $args ); | |
?> | |
<?php if ( $related_posts->have_posts() ): ?> | |
<h3> Related Posts</h3> | |
<ul> | |
<?php while ( $related_posts->have_posts() ): $related_posts->the_post(); ?> | |
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?> </a></li> | |
<?php endwhile; ?> | |
</ul> | |
<?php endif; ?> | |
<?php | |
// reset the query | |
wp_reset_postdata(); | |
// get the ob contents | |
$out = ob_get_contents(); | |
ob_end_clean(); | |
return do_shortcode( $out ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment