{"id":1806,"date":"2022-05-18T03:07:04","date_gmt":"2022-05-18T03:07:04","guid":{"rendered":"https:\/\/shaplakanon.com\/wpsupport\/?p=1806"},"modified":"2022-05-18T03:07:06","modified_gmt":"2022-05-18T03:07:06","slug":"how-to-modify-wp_query-with-pre_get_posts-action-hook","status":"publish","type":"post","link":"https:\/\/shaplakanon.com\/wpsupport\/how-to-modify-wp_query-with-pre_get_posts-action-hook\/","title":{"rendered":"How to modify wp_query with pre_get_posts action hook?"},"content":{"rendered":"\n
pre_get_posts is an action hook that runs before wp query. You can modify wp_query to using this action hook. Below are few examples:<\/p>\n\n\n\n
Exclude Single Posts by ID From Home Page:<\/strong><\/p>\n\n\n\n Exclude Pages from Search Results:<\/strong><\/p>\n\n\n\n Only Display Search Results After Specific Date:<\/strong><\/p>\n\n\n\n pre_get_posts is an action hook that runs before wp query. You can modify wp_query to using this action hook. Below<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[51],"tags":[335,333,334],"class_list":["post-1806","post","type-post","status-publish","format-standard","hentry","category-wordpress","tag-modify-wordpress-query","tag-pre_get_posts","tag-wp_query"],"yoast_head":"\nfunction exclude_single_posts_home($query) {\r\n if ( $query->is_home() && $query->is_main_query() ) {\r\n $query->set( 'post__not_in', array( 7, 11 ) );\r\n }\r\n}\r\nadd_action( 'pre_get_posts', 'exclude_single_posts_home' );<\/code><\/pre>\n\n\n\n
function search_filter($query) {\r\n if ( ! is_admin() && $query->is_main_query() ) {\r\n if ( $query->is_search ) {\r\n $query->set( 'post_type', 'post' );\r\n }\r\n }\r\n}\r\nadd_action( 'pre_get_posts', 'search_filter' );<\/code><\/pre>\n\n\n\n
function date_search_filter($query) {\r\n if ( ! is_admin() && $query->is_main_query() ) {\r\n if ( $query->is_search ) {\r\n $query->set( 'date_query', array(\r\n array(\r\n 'after' => 'May 17, 2019', \r\n )\r\n ) ); \r\n }\r\n }\r\n}\r\nadd_action( 'pre_get_posts', 'date_search_filter' );<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"