Quick WordPress Category Hacks

ks11732I’ve spent the last couple of days working on a doozy of a WordPress theme. It consisted of various category hacks on both posts and pages (yes, you can add blog posts to the static pages!). I ended up searching all over the internet for what I was looking for, and had to mix and max solutions to come up with what I needed. I thought everyone would benefit from having these in one handy place.

Exclude Categories From Blog

Very handy. I was creating a site completely in WordPress, that needed a portfolio section. We were trying to make the portfolio dynamic with posts, so we wanted to exclude all posts in the blog that were in the portfolio category. Put this snippet in your functions.php file, and replace “3” with your category. (Keep the minus sign with it)

function exclude_category($query) {

if ( $query->is_home ) {

$query->set('cat', '-3');

}

Include Category Posts on Static Pages

Place this code in your page.php, along with the post call from your index.php to have it include blog posts in a certain category. You can control which pages the posts appear on!


// page id 4 will get category ID 3 posts

if (is_page('4') ) {

$cat = array(3);

}

// if the page id is 4, than only show 9 posts
if (is_page('4') ) {

$showposts = 9; // -1 shows all posts

$do_not_show_stickies = 1; // 0 to show stickies

$args=array(

'category__in' => $cat,

'showposts' => $showposts,

'caller_get_posts' => $do_not_show_stickies

);

$my_query = new WP_Query($args);

}

?>

have_posts() ) : ?>

have_posts()) : $my_query->the_post(); ?>

in_the_loop = true;

?>

List Children of Categories As Links

If you want to print a list of only one category’s children on a certain page, place this in page.php:

<?php wp_list_categories('show_count=0&child_of=3&title_li='); ?>

If you want to print a list of only one category’s children on every page:

Only Show A Certain Number Of Posts on a Static Page

Stick this code below your category call, or above the whole query.

// if the page id is 4, than only show 9 posts

if (is_page('4') ) {

$showposts = 9; // -1 shows all posts

$do_not_show_stickies = 1; // 0 to show stickies

$args=array(

'category__in' => $cat,

'showposts' => $showposts,

'caller_get_posts' => $do_not_show_stickies

);

$my_query = new WP_Query($args);

}

?>