I am trying to find a way to limit the amount of categories the [post_categories] shortcode outputs. Is there a way to do this? For example if a post belongs to 10 other categories it current displays every category, is there a way to limit it to only list x amount of categories? if so, how?
This was very new for me and I loved the idea. For this reason I published this tips. Drop the following code in your functions.php or any other helpers file(.php).
add_shortcode( 'limited_post_categories', 'gd_limited_post_categories' );
function gd_limited_post_categories( $atts ) {
global $wp_rewrite;
$thelist = '';
$rel = ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) ? 'rel="category tag"' : 'rel="category"';
$defaults = array(
'sep' => ', ',
'before' => __( 'Filed Under: ', 'genesis' ),
'after' => '',
'limit' => 3,
'exclude' => '',
);
$atts = shortcode_atts( $defaults, $atts, 'post_categories' );
//* Fetching the categories of current post
$categories = get_the_terms( false, 'category' );
if ( ! $categories || is_wp_error( $categories ) )
$categories = array();
$categories = array_values( $categories );
foreach ( array_keys( $categories ) as $key ) {
//* excluding some terms from array
if( ! empty( $atts['exclude'] ) || $atts['exclude'] != '' ) {
$exclude_cats = explode( ',', $atts['exclude'] );
if( in_array( $categories[ $key ]->term_id, (array) $exclude_cats ) ) {
unset( $categories[ $key ] );
continue;
}
}
_make_cat_compat( $categories[$key] );
}
//* Removing the extra portion
$cats = array_splice( $categories, 0, $atts['limit'] );
//* Do nothing if no cats
if ( ! $cats ) {
return '';
}
//* Making the list
$i = 0;
foreach ( $cats as $category ) {
if ( 0 < $i )
$thelist .= $atts['sep'];
$thelist .= 'term_id ) ) . '" ' . $rel . '>' . $category->name.'';
++$i;
}
if ( genesis_html5() )
$output = sprintf( '', genesis_attr( 'entry-categories' ) ) . $atts['before'] . $thelist . $atts['after'] . '';
else
$output = '' . $atts['before'] . $thelist . $atts['after'] . '';
return apply_filters( 'genesis_post_categories_shortcode', $output, $atts );
}
I created new shortcode [limited_post_catgories] for post info/meta. You will alter default [post_categories] with this new shortcode and get the desired output on your site.
By default new shortcode will show the 3 categories. But you can alter the value by passing the limit parameter into the shortcode e.g. [limited_post_catgories limit=1].
Explaining the steps. First I am retrieving post categories using WordPress functions get_the_terms. I am getting the all categories of current post in array. Then I am removing the unwanted portion from array by PHP function array_splice(). Run a foreach loop using truncated array and generate the categories list.