Skip to main content
We are Brand SEO Beijing serving international business, your marketing partner, Contact us by

Get the previous and next articles in the same category of the current article

The code is modified from the get_adjacent_post function that comes with wp. The get_adjacent_post function is the basic function that wordpress uses to get the previous and next articles.
Function: Get the first and last articles under the same category of the current article
Parameters: Get the previous article when $previous is true, and get the next article when it is false
$number is the number of articles to get
function code:

//author: ashuwp function ashu_get_adjacent_posts( $previous = true, $number = 1 ) { //global current article variable $post and database operation class wpdb global $post, $wpdb; if ( empty( $post ) ) return null; $current_post_date = $post->post_date;//Time of current post $join = ''; $posts_in_ex_cats_sql = ''; //Join table $join = " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr .object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id"; //Get the category of the current article, it can belong to multiple categories, if it is a custom taxonomy, replace the category with the corresponding taxonomy Just $cat_array = wp_get_object_terms($post->ID, 'level', array('fields' => 'ids')); $join .= " AND tt.taxonomy = 'level' AND tt.term_id IN (" . implode(',', $cat_array) . ")"; //Determine whether the time is greater than or rainy $op = $previous ? '<' : '>'; //Sort $order = $previous ? 'DESC' : 'ASC'; $where = $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' ", $current_post_date, $post->post_type); $ sort = "ORDER BY p.post_date $order LIMIT 0, $number"; $query = "SELECT p.* FROM $wpdb->posts AS p $join $where $sort"; $query_ key = 'adjacent_post_' . md5($query); $result = wp_cache_get($query_key, 'counts'); if ( false !== $result ) return $result; $result = $wpdb->get_results("SELECT p .* FROM $wpdb->posts AS p $join $where $sort"); if ( null === $result ) $result = ''; wp_cache_set($query_key, $result, 'counts'); return $result ; }

Just put the function in the functions.php file of the theme, and when the function is called, it will return an array. Example:

The tutorials preceding this one are  ID).'" title="'.$postt->post_title.'">'.$postt->post_title.' '; }; ?>The tutorials that follow this tutorial are  ID).'" title="'.$postt->post_title.'">'.$postt->post_title.' '; }; ?>


Back to Top