如何在WordPress的Press自定义文章类型常规循环中排除release术语文章?
Solution: Exclude Specific Term from Press CPT Main Archive Loop
Got it, let's fix this for you. The core challenge here is targeting only the main archive loop for your "Press" custom post type (CPT) without interfering with any other custom loops you might have on your site. Here's the cleanest, most efficient code to add to your theme's functions.php file:
add_action( 'pre_get_posts', 'exclude_release_press_posts' ); function exclude_release_press_posts( $query ) { // Target only the main query on the Press CPT archive page if ( $query->is_main_query() && is_post_type_archive( 'press' ) ) { // Exclude posts tagged with the 'release' term in 'presstype' taxonomy $query->set( 'tax_query', array( array( 'taxonomy' => 'presstype', 'field' => 'slug', 'terms' => 'release', 'operator' => 'NOT IN', ) ) ); } }
How This Works:
pre_get_postsHook: This runs right before WordPress executes the main query, so we can modify parameters without running extra database queries.$query->is_main_query(): Ensures we only adjust the default loop (like the one onmydomain.com/press)—your custom loops (usingnew WP_Query()) won't be touched.is_post_type_archive('press'): Confirms we're on the archive page for your "Press" CPT, so the rule doesn't apply elsewhere.- Tax Query: The
NOT INoperator tells WordPress to exclude any posts assigned to thereleaseterm in thepresstypetaxonomy.
Quick Adjustments (If Needed):
- To exclude multiple terms, just update the
termsvalue to an array:'terms' => array('release', 'press-statement') - If you need to target a different CPT or taxonomy, swap out the
pressandpresstypevalues respectively.
内容的提问来源于stack exchange,提问作者Ignae Maemstein
相关产品推荐
相关产品推荐

