Skip to content

Instantly share code, notes, and snippets.

@k4zuki02h4t4
Created September 13, 2016 13:23
Show Gist options
  • Save k4zuki02h4t4/5f30ff030ae8e75a151ea8d0cfdc965b to your computer and use it in GitHub Desktop.
Save k4zuki02h4t4/5f30ff030ae8e75a151ea8d0cfdc965b to your computer and use it in GitHub Desktop.
[WordPress] Shortcode - Post list.
<?php
/**
* Shortcode - Post list.
*
* @param array $atts The Shortcode arguments.
*
* @return string
*/
function kuck1u_shortcode_postlist( $atts ) {
$atts = shortcode_atts( array(
'type' => 'post',
'tax' => 'category',
'terms' => '',
), $atts, 'postlist' );
$atts['type'] = sanitize_key( $atts['type'] );
$atts['tax'] = sanitize_key( $atts['tax'] );
$atts['terms'] = array_map( 'sanitize_key', explode( ',', $atts['terms'] ) );
$args = array(
'post_type' => $atts['type'],
'tax_query' => array(
array(
'taxonomy' => $atts['tax'],
'field' => 'slug',
'terms' => $atts['terms'],
),
),
'post_status' => 'publish',
'nopaging' => true,
'posts_per_page' => '-1',
);
$cache_key = 'kuck1u_47888_shortcode_post';
$cache = get_transient( $cache_key );
$output = array();
if ( empty( $atts['terms'][0] ) ) {
$args['tax_query'][0]['operator'] = 'NOT IN';
}
if ( false === $cache ) {
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
ob_start();
get_template_part( 'content', 'search' );
$output[] = trim( ob_get_contents() );
ob_end_clean();
}
}
wp_reset_postdata();
$output = implode( PHP_EOL, $output );
set_transient( $cache_key, $output, 12 * HOUR_IN_SECONDS );
} else {
$output = $cache;
}
return $output;
}
add_shortcode( 'postlist', 'kuck1u_shortcode_postlist' );
@k4zuki02h4t4
Copy link
Author

k4zuki02h4t4 commented Sep 13, 2016

How to use

[postlist terms="design,illust"] 
[postlist type="portfolio" tax="portfolio-cat" terms="design,illust"] 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment