作为记录,我刚刚找到了一种新的/不同的方法来实现这个目标。这并不完全相同,但它确实允许我在原始循环中的每X个帖子之后插入一个新的帖子类型。
这是来源:https://www.gowp.com/blog/inserting-custom-posts-loop/
该方法是通过下面的代码完成的,它本质上是将一个新的自定义post类型注入到循环中,无论分页如何,它似乎都能工作。
add_action( \'wp\', \'fs_only_do_on_homepage\' );
function fs_only_do_on_homepage() {
if( is_front_page() ) {
/* change the query to inject ads after every X frequency */
// https://www.gowp.com/blog/inserting-custom-posts-loop/
add_filter( \'the_posts\', \'fs_insert_ads\', 10, 2 );
function fs_insert_ads( $posts, $query ) {
// We don\'t want our filter to affect post lists in the admin dashboard
if ( is_admin() ) return $posts;
// We also only want our filter to affect the main query
if ( ! is_main_query() ) return $posts;
// Set a variable for the frequency of the insertion which we\'ll use in some math later on
$freq = 2;
/* Retrieve the ads, and calculate the posts_per_page on the fly,
* based on the value from the original/main query AND our frequency
* this helps ensure that the inserted posts stay in sync regardless of pagination settings
*/
$args = array(
\'post_type\' => \'fs_ads\',
\'posts_per_page\' => floor( $query->query_vars[\'posts_per_page\'] / $freq ),
\'paged\' => ( $query->query_vars[\'paged\'] ) ? $query->query_vars[\'paged\'] : 1,
\'orderby\' => \'menu_order\',
\'order\' => \'ASC\',
\'meta_key\' => \'status\',
\'meta_value\' => \'enable\',
);
// inserts the ads into the $posts array, using array_slice() ... and do some math to ensure they are inserted correctly
if ( $fs_ads = get_posts( $args ) ) {
$insert = -1;
foreach ( $fs_ads as $fs_ad ) {
$insert = $insert + ( $freq + 1 );
array_splice( $posts, $insert, 0, array( $fs_ad ) );
}
}
return $posts;
} // end the fs_insert_ads function
} // end checking is_home
} // end the fs_only_do_on_homepage function
我确实无法说出哪个项目在哪个帖子之间,但它确实实现了我最初的目标,即在每X个帖子之后,尝试将自定义帖子类型注入到我的循环中。