Skip to content

Commit

Permalink
New filter: crp_fill_random_posts
Browse files Browse the repository at this point in the history
Fixes #10
  • Loading branch information
ajaydsouza committed Apr 19, 2022
1 parent a3e6891 commit 18b4ac4
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
29 changes: 28 additions & 1 deletion includes/class-crp-query.php
Original file line number Diff line number Diff line change
Expand Up @@ -820,6 +820,32 @@ public function the_posts( $posts, $query ) {
$posts = array_merge( $extra_posts, $posts );
}

/**
* Set the flag if CRP should fill random posts if there is a shortage of related posts.
*
* @since 3.2.0
*
* @param bool $fill_random_posts Fill random posts flag. Default false.
* @param WP_Post[] $posts Array of post objects.
* @param WP_Query $query The WP_Query instance.
*/
$fill_random_posts = apply_filters( 'crp_fill_random_posts', false, $posts, $query );

if ( $fill_random_posts ) {
$no_of_random_posts = $this->query_args['limit'] - count( $posts );
if ( $no_of_random_posts > 0 ) {
$random_posts = get_posts(
array(
'fields' => $query->get( 'fields' ),
'orderby' => 'rand',
'numberposts' => $no_of_random_posts,
'post_type' => $query->get( 'post_type' ),
)
);
$posts = array_merge( $posts, $random_posts );
}
}

/**
* Filter array of WP_Post objects before it is returned to the CRP_Query instance.
*
Expand All @@ -828,8 +854,9 @@ public function the_posts( $posts, $query ) {
*
* @param WP_Post[] $posts Array of post objects.
* @param array $args Arguments array.
* @param WP_Query $query The WP_Query instance.
*/
return apply_filters( 'crp_query_the_posts', $posts, $this->query_args );
return apply_filters( 'crp_query_the_posts', $posts, $this->query_args, $query );
}
}
endif;
1 change: 1 addition & 0 deletions readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ You can insert the related posts anywhere in your post using the `[crp]` shortco
* New option to limit posts to the primary category/term. The plugin checks if either Yoast, Rank Math, The SEO Framework or SEOPress are active. If none of these are active, the plugin will pick the first category provided by `get_the_terms()`
* New option to show the primary category/term
* New option in metabox to enter a comma-separated list of post IDs to exclude from the related posts
* New filter `crp_fill_random_posts` (default:false) which can be used to fill random posts if the number of related posts is less than the limit set

* Enhancements/modifications:
* `post_title` and `post_content` fields are only used if *Use content* option is set
Expand Down

0 comments on commit 18b4ac4

Please sign in to comment.