如何使用POSTS_PER_PAGE对数组进行切片?

时间:2017-08-01 作者:David Cring

下面的代码显示了wp gallery的所有图像及其大小,但它不是我想要的。

function get_images_high_data() {

    $args = array(
        \'post_type\' => \'attachment\',
        \'post_mime_type\' => \'image/jpeg,image/jpg,image/png\',
        \'post_status\' => \'inherit\',
        \'posts_per_page\' => -1,
        \'orderby\' => \'id\',
        \'order\' => \'ASC\'
    );

    // Get all the available thumbnail sizes
    $sizes = get_intermediate_image_sizes();

    // Query the attachments
    $query_images = new WP_Query( $args );

    $images = array();

    // Run a loop
    if ( $query_images->have_posts() ){

        while ($query_images->have_posts()){

            $query_images->the_post();

            // For each attachment size, store its URL in an array
            foreach ( $sizes as $key => $size ) {

                $thumbnails[$key] = wp_get_attachment_image_src( get_the_ID(), $size)[0];
            }

            $images = array_merge( $thumbnails , $images );
        }

        return $images;
    }
}
返回的数组如下所示:

[0] => thumbnail-url,
[1] => medium-url,
[2] => large-url,
[3] => thumbnail-url,
[4] => medium-url,
[5] => large-url,
但当我设定\'posts_per_page\' => 1 它是这样显示的

    [0] => thumbnail-url,
    [1] => medium-url,
    [2] => large-url,
但我希望输出如下。

 [0] => thumbnail-url,
如果我设置\'posts_per_page\' => 2 它是这样显示的

 [1] => medium-url,
 [2] => large-url,

1 个回复
SO网友:Johansson

正如我在你的previous question, 设置每页的帖子对您没有帮助。然而,有一个解决方法。

不要直接设置每页的帖子,而是使用变量并进行更改。然后使用相同的变量对数组进行切片。例如:

$per_page = 2;
// Use the $per_page value to set the posts per page
$args = array(
    \'posts_per_page\' => $per_page,
);
// The rest of your code here

    // Now, before returning the images, slice the array using
    // the variable we set before
    $images = array_slice($images, 0, $per_page);
    return $images;

结束

相关推荐

Virtual Pages plugins

我很难让插件正常工作Virtual Pages (WordPress插件可简化虚拟页面的创建)我确实进行了编辑,根据查询创建了一个循环。add_action( \'gm_virtual_pages\', function( $controller ) { /* Creating virtuals pages for companies */ $args = array( \'post_type\' => array(\'companies\',), \'post_status\'