Skip to content

Instantly share code, notes, and snippets.

@barrykooij
Last active January 26, 2025 10:49
Show Gist options
  • Save barrykooij/ad1a7f4c8cb7170da7df to your computer and use it in GitHub Desktop.
Save barrykooij/ad1a7f4c8cb7170da7df to your computer and use it in GitHub Desktop.
Exclude RP4WP categories
function rp4wp_exclude_category( $sql, $post_id, $post_type ) {
global $wpdb;
if ( 'post' !== $post_type ) {
return $sql;
}
$sql_replace = sprintf( "
INNER JOIN " . $wpdb->term_relationships . " ON (R.`post_id` = " . $wpdb->term_relationships . ".object_id)
INNER JOIN " . $wpdb->term_taxonomy . " ON (" . $wpdb->term_relationships . ".term_taxonomy_id = " . $wpdb->term_taxonomy . ".term_taxonomy_id)
WHERE 1=1
AND " . $wpdb->term_taxonomy . ".taxonomy = 'category'
AND " . $wpdb->term_taxonomy . ".term_id NOT IN ( %s )
", " 100,200,300 " );
return str_ireplace( 'WHERE 1=1', $sql_replace, $sql );
}
add_filter( 'rp4wp_get_related_posts_sql', 'rp4wp_exclude_category', 11, 3 );
@kupietools
Copy link

kupietools commented Jan 26, 2025

I just spent about two hours trying to get this to work and unfortunately it appears not to work at all. I changed

	AND " . $wpdb->term_taxonomy . ".term_id NOT IN ( %s )
	", " 100,200,300 " );

to

	AND " . $wpdb->term_taxonomy . ".term_id IN ( %s )
	", " 1 " );

which should have prevented most of my posts from appearing. I then re-ran the wizard to cache and link the posts and it's still including all the posts.

UPDATE: I just added some logging and ran a test. It looks like rp4wp_get_related_posts_sql is never called, not when the posts are cached and linked, not when the page is rendered, never.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment