Created
September 13, 2016 13:23
-
-
Save k4zuki02h4t4/5f30ff030ae8e75a151ea8d0cfdc965b to your computer and use it in GitHub Desktop.
[WordPress] Shortcode - Post list.
This file contains 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 | |
/** | |
* 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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use