[wp-trac] [WordPress Trac] #51860: wp-sitemap includes empty post entries returned by filters
WordPress Trac
noreply at wordpress.org
Tue Nov 24 18:29:09 UTC 2020
#51860: wp-sitemap includes empty post entries returned by filters
-------------------------+------------------------------
Reporter: jsmoriss | Owner: (none)
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Sitemaps | Version: 5.5
Severity: normal | Resolution:
Keywords: | Focuses:
-------------------------+------------------------------
Comment (by jsmoriss):
Replying to [comment:1 swissspidy]:
> > return an empty array (as another way to exclude a post from the
sitemap, for example)
>
> Just for reference, the filter was actually deliberately implemented so
that this is _not_ possible as it would mess with pagination. So it was
never recommended to return an empty array. Instead, the WP_Query args
should be filtered to exclude posts.
The 'wp_sitemaps_posts_query_args' filter is applied when counting the
maximum number of pages, and for each page, so unless a filter hook is
coded properly, it has the potential to affect performance (having to be
applied for the counter and each page).
Using a static cache, I was able to create a filter that, I believe, will
avoid affecting performance too much. I'll leave this example here, in
case anyone else needs to exclude many posts, terms, or users from the
query. Note that the excluded post IDs are merged from the cache, which
allows other filters to exclude additional post IDs before/after this
filter.
{{{
public function wp_sitemaps_posts_query_args( $args, $post_type ) {
static $local_cache = array();
if ( ! isset( $local_cache[ $post_type ] ) ) {
$local_cache[ $post_type ] = array();
$query = new WP_Query( array_merge( $args, array(
'fields' => 'ids', // Return an array
of post ids.
'no_found_rows' => true, // Skip counting
total rows found.
) ) );
foreach ( $query->posts as $post_id ) {
if ( is_post_excluded_example_function( $post_id )
) {
$local_cache[ $post_type ][] = $post_id;
}
}
}
if ( ! empty( $local_cache[ $post_type ] ) ) {
$args[ 'post__not_in' ] = empty( $args[ 'post__not_in' ] )
? $local_cache[ $post_type ] :
array_merge( $args[ 'post__not_in' ],
$local_cache[ $post_type ] );
}
return $args;
}
}}}
--
Ticket URL: <https://core.trac.wordpress.org/ticket/51860#comment:3>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list