Advertisement
arie_cristianD

exclude sponsored posts

Feb 12th, 2024
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.64 KB | None | 0 0
  1. /**
  2.  * Fetch IDs of sponsored posts to exclude from main and feed queries.
  3.  */
  4. function get_sponsored_post_ids() {
  5.     $args = array(
  6.         'post_type'      => 'post',
  7.         'posts_per_page' => -1,
  8.         'fields'         => 'ids',
  9.         'meta_query'     => array(
  10.             array(
  11.                 'key'     => 'jnews_single_post',
  12.                 'value'   => '"sponsored_post";s:1:"1";',
  13.                 'compare' => 'LIKE',
  14.             ),
  15.         ),
  16.     );
  17.  
  18.     $query = new WP_Query( $args );
  19.     return $query->posts;
  20. }
  21. $exclude_posts = array();
  22. if ( ! is_admin() ) {
  23.     $exclude_posts = get_sponsored_post_ids();
  24. }
  25.  
  26.  
  27. /**
  28.  * Exclude sponsored posts from main and category queries.
  29.  */
  30. function exclude_specific_posts( $query ) {
  31.     if ( ! is_admin() && ( $query->is_front_page() || $query->is_category() ) ) {
  32.         global $exclude_posts;
  33.         $query->set( 'post__not_in', $exclude_posts );
  34.     }
  35. }
  36. add_action( 'pre_get_posts', 'exclude_specific_posts' );
  37.  
  38. /**
  39.  * Exclude sponsored posts from RSS feed.
  40.  */
  41. function exclude_specific_posts_from_feed( $query ) {
  42.     if ( $query->is_feed() ) {
  43.         global $exclude_posts;
  44.         $query->set( 'post__not_in', $exclude_posts );
  45.     }
  46. }
  47. add_action( 'pre_get_posts', 'exclude_specific_posts_from_feed' );
  48.  
  49. /**
  50.  * Disable comments RSS feed.
  51.  */
  52. function disable_comments_rss() {
  53.     global $wp_rewrite;
  54.     $wp_rewrite->feeds = array_diff( $wp_rewrite->feeds, array( 'comments_rss2' ) );
  55. }
  56. add_action( 'init', 'disable_comments_rss', 1 );
  57.  
  58. /**
  59.  * Redirect comments RSS feed to homepage.
  60.  */
  61. function redirect_comments_rss_to_homepage() {
  62.     if ( is_comment_feed() ) {
  63.         wp_redirect( home_url(), 301 );
  64.         exit;
  65.     }
  66. }
  67. add_action( 'template_redirect', 'redirect_comments_rss_to_homepage' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement