Skip to content

Instantly share code, notes, and snippets.

@addisonhall
Last active November 4, 2017 20:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save addisonhall/344ac21f17d5fb7151dbef10a30f775a to your computer and use it in GitHub Desktop.
Save addisonhall/344ac21f17d5fb7151dbef10a30f775a to your computer and use it in GitHub Desktop.
WordPress shortcode example: output custom post type list by custom taxonomy
<?php
/**
* Partial for custom_post_type_list shortcode output.
*
* @package ChildTheme
*/
if ( ! defined( 'ABSPATH' ) ) exit; ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
/**
* Theme shortcode for outputting custom post type list.
*
* This file is normally included from functions.php
*
* @package ChildTheme
* @link https://codex.wordpress.org/Shortcode_API
*/
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Output custom post type.
* [custom_post_type_list category='category-slug']
*/
function ahd_custom_post_type_list_func( $atts ) {
$a = shortcode_atts( array(
'category' => '',
), $atts );
$cpt_name = 'custom_post_type_name';
$tax_name = 'custom_taxonomy_name';
$tax_slug = $a[ 'category' ];
$no_results_string = 'There are no results.';
if ( $tax_slug ) {
$args = array (
'post_type' => $cpt_name,
'order' => 'ASC',
'orderby' => 'title',
'tax_query' => array(
array (
'taxonomy' => $tax_name,
'field' => 'slug',
'terms' => $tax_slug
)
)
);
} else {
$args = array (
'post_type' => $cpt_name,
'order' => 'ASC',
'orderby' => 'title',
);
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
ob_start();
echo '<ul>';
while ( $query->have_posts() ) : $query->the_post();
include get_stylesheet_directory() . '/partials/content-cpt-output-list.php';
endwhile;
echo '</ul>';
wp_reset_postdata();
$output = ob_get_clean();
} else {
$output = $no_results_string;
}
return $output;
}
add_shortcode( 'custom_post_type_list', 'ahd_custom_post_type_list_func' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment