Category Archives: Uncategorized

Limit the number of sticky posts appearing on site

Code to limit the number of sticky posts shown in a page

/* Get all sticky posts */
$sticky = get_option( ‘sticky_posts’ );

/* Sort the stickies with the newest ones at the top */
rsort( $sticky );

/* Get the 2 newest stickies (change 5 for a different number) */
$sticky = array_slice( $sticky, 0, 5 );

/* Query sticky posts */
query_posts( array( ‘post__in’ => $sticky, ‘caller_get_posts’ => 1 ) );
?>

Restrict categories in wp drop down categories function

The function wp_dropdown_categories is used to display all categories as a drop down.

If a site uses different custom post types and if we want to show only categories used by a particular custom post type, we can use the following code. The following code displays categories used by the post type ‘highlight’.


$exclusive_post_type = 'highlights';
$exclude_cats = array();
$nonemptycats = get_terms( 'category' );
foreach( $nonemptycats as $term ){
$term_id = $term->term_id;
$term_objects = get_objects_in_term( $term_id, 'category' );
$exclude_term = true;

foreach( $term_objects as $post_id ){
if ( $exclusive_post_type === get_post_type( $post_id ) ){
$exclude_term = false;

break;
}
}
if ( $exclude_term ) $exclude_cats[] = $term_id;
}
$args = array(
'show_option_none' => 'All categories',
'orderby' => 'name',
'hide_empty' => 1,
'exclude' => $exclude_cats,
'hierarchical' => 1,
'hide_if_empty' => true
);
wp_dropdown_categories( $args );