Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all articles
Browse latest Browse all 8245

igogra on "Custom Ordering Post Link Functions"

$
0
0

Hi,

I'm using a custom post type to hold products, each product holds a name via a custom field. When I display the product via its singular template it would be nice to have a next & previous link to go through those products, but it should go through them in order of their name. Currently that’s not possible as they would be ordered by their publishing dates.

So I added the following code in functions.php, but it's not working, I don't know if this has to be made in a different way:

if(is_singular('products')) {
	add_filter('get_previous_post_join', 'rt_post_join');
	add_filter('get_next_post_join', 'rt_post_join');
	add_filter('get_previous_post_where', 'rt_prev_post_where');
	add_filter('get_next_post_where', 'rt_next_post_where');
	add_filter('get_previous_post_sort', 'rt_prev_post_sort');
	add_filter('get_next_post_sort', 'rt_next_post_sort');
}

function rt_post_join($join, $isc, $ec) {
	global $wpdb;

	$join = " INNER JOIN $wpdb->postmeta AS pm ON pm.post_id = p.ID";
	return $join;
}

function rt_prev_post_where($w) {
	global $wpdb, $post;

	$prd = get_post_meta($post->ID, 'data_product_name_product', true);
	$w = $wpdb->prepare(" WHERE pm.meta_key = 'data_product_name_product' AND pm.meta_value < '$prd' AND p.post_type = 'products' AND p.post_status = 'publish'");
	return $w;
}

function rt_next_post_where($w) {
	global $wpdb, $post;

	$prd = get_post_meta($post->ID, 'data_product_name_product', true);
	$w = $wpdb->prepare(" WHERE pm.meta_key = 'data_product_name_product' AND pm.meta_value > '$prd' AND p.post_type = 'products' AND p.post_status = 'publish'");
	return $w;
}

function rt_prev_post_sort($o) {
	$o = "ORDER BY pm.meta_value DESC LIMIT 1";
	return $o;
}
function rt_next_post_sort($o) {
	$o = "ORDER BY pm.meta_value ASC LIMIT 1";
	return $o;
}

And in my single page of products (single-products.php) I added the following code to display the pagination links:

<?php next_post_link('%link', 'Next product'); ?>
<?php previous_post_link('%link','Previous product'); ?>

Thanks.


Viewing all articles
Browse latest Browse all 8245

Trending Articles