[英]Splitting the wordpress loop in gutenberg blocks created with acf
我有一个关于使用高级自定义字段在 Gutenberg 块中显示帖子和自定义帖子的问题。 我想查询一个帖子类型的所有帖子,但是拆分循环,因为我需要为各个帖子提供不同的布局。 我想在具有不同行和列高度的网格中显示帖子(见下图),并且不为此使用外部 css,因为我正在使用 TailwindCSS。 为此,我通常会使用 function 来拆分循环,如下所述: https://vanrossum.dev/20-splitting-the-wordpress-loop
//functions.php
function posts_from_loop( $amount, $callback ) {
global $wp_query;
$count = 0;
while ( ( $count < $amount ) && ( $wp_query->current_post + 1 < $wp_query->post_count ) ) {
$wp_query->the_post();
$callback();
$count++;
}
}
并像下面这样使用它:
//home.php
<div class="grid">
<?php
posts_from_loop( 2, function() {
get_template_part( 'partials/post-w50' );
});
?>
</div>
<div class="grid">
<?php
posts_from_loop( 3, function() {
get_template_part( 'partials/post-w33' );
});
?>
</div>
<?php while ( have_posts() ) {
the_post();
?>
<?php get_template_part( 'partials/post-w100' ); ?>
<?php } ?>
但是,function 在 Gutenberg 块内不起作用,也不适用于自定义帖子类型。 我试图像下面这样设置它
//block.php
<?php
$args = array(
'post_type' => 'posts',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
);
$loop = new WP_Query($args);
?>
<?php if ($loop->have_posts()) : ?>
<div class="container mb-2">
<?php
posts_from_loop(1, function () { ?>
<?php get_template_part('template-parts/partials/post', "featured"); ?>
<?php }); ?>
</div>
<div class="container grid grid-cols-1 gap-2 mx-auto md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
<?php
posts_from_loop(4, function () {
get_template_part('template-parts/partials/post', 'color');
});
?>
<?php while (have_posts()) {
the_post();
?>
<?php get_template_part('template-parts/partials/post', "image"); ?>
<?php } ?>
</div>
<?php endif ?>
会很好,如果有人可以帮助我
function posts_from_loop
作用于global
查询,您有一个自定义查询。 最快的解决方法是将自定义查询作为可选参数传递,如果未提供则回退到全局(对于 BC 具有已经使用该函数的任何代码)。
function posts_from_loop( $amount, $callback, $query = null ) {
if(!$query) {
global $wp_query;
$query = $wp_query;
}
$count = 0;
while ( ( $count < $amount ) && ( $query->current_post + 1 < $query->post_count ) ) {
$query->the_post();
$callback();
$count++;
}
}
posts_from_loop(
4,
function () {
get_template_part('template-parts/partials/post', 'color');
},
$loop
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.