fauzanjeg

Exclude terms from the prev-next post query

Jun 4th, 2025
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.22 KB | None | 0 0
  1. <?php
  2. if ( ! function_exists( 'exclude_terms_from_next_post' ) ) {
  3.     /**
  4.      * Exclude terms from the prev-next post query.
  5.      *
  6.      * This function modifies the prev-next post query to exclude posts that share
  7.      * any of the terms.
  8.      *
  9.      * @param array $excluded_terms Array of term IDs to exclude.
  10.      *
  11.      * @return array Modified array of excluded term IDs.
  12.      */
  13.     function exclude_terms_from_next_post( $excluded_terms ) {
  14.         if ( empty( $excluded_terms ) && ! is_array( $excluded_terms ) ) {
  15.             $excluded_terms = array();
  16.         }
  17.  
  18.         /**
  19.          * List Categoory Slugs to Exclude
  20.          */
  21.         $terms = array(
  22.             'jnews_demo_education',
  23.             'jnews_demo_editorial',
  24.         );
  25.  
  26.         foreach ( $terms as $term ) {
  27.             /**
  28.              * Get the term object by slug
  29.              * This assumes that the terms are categories.
  30.              * If they are not, you may need to adjust this accordingly.
  31.              */
  32.             $category = get_term_by( 'slug', $term, 'category' );
  33.  
  34.             /**
  35.              * Add each term ID to the excluded terms array
  36.              */
  37.             $excluded_terms[] = $category->term_id;
  38.         }
  39.  
  40.         return $excluded_terms;
  41.     }
  42.     add_filter( 'get_previous_post_excluded_terms', 'exclude_terms_from_next_post' );
  43.     add_filter( 'get_next_post_excluded_terms', 'exclude_terms_from_next_post' );
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment