Skip to content

Instantly share code, notes, and snippets.

@kierzniak
Last active July 24, 2018 06:21
Show Gist options
  • Save kierzniak/261a86c2172480f86228fd922eebcca2 to your computer and use it in GitHub Desktop.
Save kierzniak/261a86c2172480f86228fd922eebcca2 to your computer and use it in GitHub Desktop.
Get category related posts published before given post
<?php
/**
* Class provided to get category related posts published before given post
*
* @author Motivast motivast.com
* @copyright 2018 - present, Motivast
*
* @license https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt GPL-2.0-or-later
*
* @link https://gist.github.com/kierzniak/261a86c2172480f86228fd922eebcca2
*/
/**
* Class provided to get category related posts published before given post
*/
class Motivast_Related_Posts {
/**
* Current post id
*
* @var int
*/
private static $post_id;
/**
* Get category related posts
*
* @param int $post_id Current post id
* @param int $limit How many posts should be returned
*
* @return array
*/
public static function get_category_related_posts( $post_id, $limit = 3 ) {
$cats_ids = array();
foreach( get_the_category( $post_id ) as $category ) {
$cats_ids[] = $category->cat_ID;
}
self::$post_id = $post_id;
add_filter( 'posts_where', 'Motivast_Related_Posts::only_get_posts_published_before_current_post' );
$query = new WP_Query(array(
'posts_per_page' => $limit,
'category__in' => $cats_ids,
));
remove_filter( 'posts_where', 'Motivast_Related_Posts::only_get_posts_published_before_current_post' );
return $query->posts;
}
/**
* Filter is used to add own pure SQL where clause to WP_Query SQL
*
* @param string $where Pure SQL where clause
*
* @return string
*/
public static function only_get_posts_published_before_current_post( $where ) {
global $wpdb;
$where .= $wpdb->prepare( ' AND wp_posts.ID < %d', self::$post_id );
return $where;
}
}
/**
* Get category related posts function
*
* @param int $post_id Current post id
* @param int $limit How many posts should be returned
*
* @return array
*/
function motivast_get_category_related_posts( $post_id, $limit = 3 ) {
return Motivast_Related_Posts::get_category_related_posts( $post_id, $limit );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment