wp-forge / wp-loop

一个生成器函数,使使用WordPress循环变得如梦幻般。

1.0 2020-07-09 02:53 UTC

This package is auto-updated.

Last update: 2024-09-09 12:35:38 UTC


README

一个生成器函数,使使用WordPress循环变得如梦幻般。

这个功能何时将集成到WordPress核心中?

目前尚不清楚。然而,您可以关注这个trac工单的进展。

安装

  • 运行 composer require wp-forge/wp-loop
  • 确保在您的项目中需要vendor/autoload.php文件。

用法

以下是几个使用wp_loop()函数的示例

使用全局WP_Query实例

<?php

foreach ( wp_loop() as $post ) {
	?>
	<article>
		<h1><?php the_title(); ?></h1>
		<div><?php the_content(); ?></div>
	</article>
	<?php
}

使用自定义WP_Query实例

<?php

$query = new WP_Query( [ 'post_type' => 'post' ] );

foreach ( wp_loop( $query ) as $post ) {
	?>
	<article>
		<h1><?php the_title(); ?></h1>
		<div><?php the_content(); ?></div>
	</article>
	<?php
}

循环结束后无需运行wp_reset_postdata()。即使您提前退出循环,它也会自动处理!

使用WP_Post对象数组

<?php

$query = new WP_Query( [ 'post_type' => 'post' ] );
$posts = $query->posts;

foreach ( wp_loop( $posts ) as $post ) {
	?>
	<article>
		<h1><?php the_title(); ?></h1>
		<div><?php the_content(); ?></div>
	</article>
	<?php
}

使用帖子ID数组

<?php

$query = new WP_Query( [
	'post_type' => 'post',
	'fields'    => 'ids',
] );

$post_ids = $query->posts;

foreach ( wp_loop( $post_ids ) as $post ) {
	?>
	<article>
		<h1><?php the_title(); ?></h1>
		<div><?php the_content(); ?></div>
	</article>
	<?php
}

使用迭代器

<?php

$query    = new WP_Query( [ 'post_type' => 'post' ] );
$iterator = new ArrayIterator( $query->posts );

foreach ( wp_loop( $iterator ) as $post ) {
	?>
	<article>
		<h1><?php the_title(); ?></h1>
		<div><?php the_content(); ?></div>
	</article>
	<?php
}

其他说明

wp_loop()函数旨在在foreach循环中使用。如果您需要在循环之前检查是否有结果,您可以像平时那样做。

例如

<?php

if( have_posts() ) {
    // For global query approach
}

if( $query->have_posts() ) {
    // For custom query approach
}

if( ! empty( $posts ) ) {
    // For post or post ID approach
}

if( $iterator->valid() ) {
    // For iterator approach
}

wp_loop()函数比标准的WordPress循环更进一步,会自动为每个迭代设置和恢复全局$post对象。

有关更多详细信息,请阅读这篇关于创建更好的WordPress循环的博客文章。当前的实现略有不同,但推理阐述得相当好。