WordPress pieces of code of the month

I found two pieces of code for WordPress that might come in handy from time to time.

Custom Post Types pagination for the homepage

It appears there’s a bug in WP 3.0 with the pagination on the homepage for custom post types.

When we create an archive page for a custom post type we make a page template where we use query_posts() to list them.

However, when we make try to put the pagination in place using get_query_var(‘paged’) it fails.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
global $paged;
 
//this code doesn't work
//$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
 
//this code works
if ( get_query_var('paged') )
	$paged = get_query_var('paged');
elseif ( get_query_var('page') )
	$paged = get_query_var('page');
else
	$paged = 1;
 
$args=array(
	'post_type' => 'cpt',
	'paged' => $paged,
	'posts_per_page' => 10,
	'post_status' => 'publish',
);
query_posts($args);
Thanks go to Devin Price for pointing me in the right direction.

Extend category permalinks to query for tags

While most people don’t need this, from time to time you might want to have query posts that are in category ‘x’ and are tagged with ‘y’. WordPress can query for that very easily, all we need to do is add the permalinks structure: www.example.com/category/x/tag/y/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function extend_category_tag_flush_rewrite_rules() {
	global $wp_rewrite;
	$wp_rewrite->flush_rules();
}
add_action('init', 'extend_category_tag_flush_rewrite_rules');
 
function extend_category_tag_add_rewrite_rules($wp_rewrite) {
	$rules = array();
	$structures = array(
		$wp_rewrite->get_category_permastruct() . $wp_rewrite->get_tag_permastruct(),
	);
	foreach( $structures as $s ){
		$rules += $wp_rewrite->generate_rewrite_rules($s);
	}
	$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'extend_category_tag_add_rewrite_rules');

You can add this code in your function.php file the theme came with.

Code based on: sltaylor.co.uk/blog/

2 thoughts on “WordPress pieces of code of the month

Leave a Reply

Your email address will not be published. Required fields are marked *