Skip to content

Instantly share code, notes, and snippets.

@sectsect
Last active October 19, 2015 02:12
Show Gist options
  • Save sectsect/2f517b762613f8776085 to your computer and use it in GitHub Desktop.
Save sectsect/2f517b762613f8776085 to your computer and use it in GitHub Desktop.
Get the Previous / Next Post link by Custom-Field on WP.
<?php
function get_prev_post_cf($link="&laquo; %link", $title="%title", $post_type="post", $meta_key, $meta_value, $label) {
global $wpdb, $post;
$prev = $wpdb->get_row($wpdb->prepare("
SELECT ID, post_title
FROM $wpdb->posts p
LEFT OUTER JOIN $wpdb->postmeta pm on p.ID = pm.post_id
WHERE post_type = '{$post_type}'
AND post_status = 'publish'
AND post_date < '".$post->post_date."'
AND meta_key = '{$meta_key}'
AND meta_value = '{$meta_value}'
ORDER BY post_date
DESC LIMIT 1;
"));
if($prev) {
// $title = preg_replace('/%title/',$prev->post_title, $title);
echo '<li class="prev"><a href="' . get_permalink($prev->ID) . '" rel="prev">' . $label . '</a></li>';
}
}
function get_next_post_cf($link="%link &raquo;", $title="%title", $post_type="post", $meta_key, $meta_value, $label) {
global $wpdb, $post;
$next = $wpdb->get_row($wpdb->prepare("
SELECT ID, post_title
FROM $wpdb->posts p
LEFT OUTER JOIN $wpdb->postmeta pm on p.ID = pm.post_id
WHERE post_type = '{$post_type}'
AND post_status = 'publish'
AND post_date > '".$post->post_date."'
AND meta_key = '{$meta_key}'
AND meta_value = '{$meta_value}'
ORDER BY post_date
DESC LIMIT 1;
"));
if($next) {
// $title = preg_replace('/%title/',$prev->post_title, $title);
echo '<li class="next"><a href="'.get_permalink($next->ID).'" rel="next">' . $label . '</a></li>';
}
}
?>
<ul>
<?php
get_prev_post_cf('', '', 'post_type', 'customfileld_key', 'customfileld_value', '&lt; Prev');
get_next_post_cf('', '', 'post_type', 'customfileld_key', 'customfileld_value', 'Next &gt;');
?>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment