如何在Wordpress中使用图像ID数组显示分页图像?

时间:2018-10-01 09:23:19

标签: php wordpress loops pagination

编辑: 我有一个代码,此代码显示meta_post,从meta_post开始,我将显示wp_get_attachment_image的图像,每个帖子在1个数组中都有一个value_gallery,数组的值为{{ 1}}个图片,其中1个id-attr有2个或多个value_gallery用逗号隔开,所以我想进行分页,但我不知道如何实现,我在id-attr上进行了此代码,

我想使这段代码像this一样,但是此代码仍然显示“未找到”,如果有人可以帮助我,我将非常高兴

注意:meta_value single-gallery.php的值是数组ex:value_gallery 谢谢您的关注

已编辑: 从此代码中,我尝试每页显示array(1) { [0]=> string(29) "1402,1435,1398,1434,1434,1434" } (例如:每页4个),并尝试进行分页,更新代码:

meta_post

已更新2 我将再次回答这个问题 所以我尝试制作一个画廊帖子,一个画廊帖子中有一个$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $ids = get_the_ID(); $args = array('paged' => $paged , 'post__in' => array($ids)); $the_query = new WP_Query($args); if (have_posts()) : while (have_posts()) : the_post(); $metas = get_post_meta(get_the_ID(),'value_gallery',false); foreach ($metas as $meta) { $key_val = explode(",", $meta); $image_chunk = array_chunk($key_val, 3); $page = get_query_var('page'); $page = $page > 1 ? $page - 1 : 0 ; if (isset($key_val[$page])) { foreach ($image_chunk[$page] as $image) { echo "<div class='col-lg-4'>". wp_get_attachment_image($image,"cherry-thumb-a") ."</div>"; } } } endwhile; $big = 9999; echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $the_query->max_num_pages ) ); wp_reset_postdata(); endif; ,值是1个数组,例如:meta_post所以这个值是图像的array(1) { [0]=> string(29) "1402,1435,1398,1434,1434,1434" },我将尝试制作id-attr

的分页

更新了3 这是我试图用此代码制作的插图 pagination post_meta

3 个答案:

答案 0 :(得分:1)

如果要按ID的数组来获取帖子,则需要使用post__in(双下划线)。

尝试下面的代码。

//Get the string from the meta by accessing the [0]th property in it.
$value = get_post_meta(get_the_ID(),'value_gallery',false)[0]; 

// Turn it into an array of IDs
$values = explode(",",$value); 

//Get the current page number from query var 'page', or if paged is not set - use 1.
$paged = max( 1, get_query_var( 'page' ) );

$args = array(
  // Use post__in to get posts by an array of IDs
  'post__in' => $values, 

  // Limit it to 4 posts per page
  'posts_per_page' => 4, 

  // Get posts from the current page we're on
  'paged' => $paged,

  // You must set 'post_status' to 'any' (or 'inherit') to get images
  'post_status' => 'any', 

  // You must set 'post_type' to 'any' (or 'attachment') to get images
  'post_type'=> 'any', 
);

// Query for the images
$res =  new WP_Query($args); 

// If there are posts...
if ( $res->have_posts() ) { 
  // For each post
  foreach ( $res->posts as $image ) { 
    // Echo the post
    echo wp_get_attachment_image( $image->ID ); 
  }

  // Echo link pagination
  echo paginate_links( array(

    // Set the base for the page links
    'base'    => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ), 

    // Get max amount of pages from the WP_Query
    'total'   => $res->max_num_pages, 

    // Use the current page number in pagination as well
    'current' => $paged, 

    // Set the format 
    'format'  => '?paged=%#%', 
  ) );
// If there are no posts
} else { 
  // Echo "not found"
  echo "not found"; 
}

如果post_meta value_gallery包含重复的ID,则WP_Query将无法多次提取相同的帖子。如果需要多次显示同一张图片,则需要创建自己的函数以查看数组中的哪些项属于当前页面。

这是一个可以实现此功能的示例。

// Function to paginate an array of IDs
function wpse_52588027_paginated_post_ids($posts_per_page, $paged, $post_ids) {
  // If current page is higher than possible
  if ($paged > ceil(count($post_ids) / $posts_per_page)) {
    // Set current page to last possible page
    $paged = ceil(count($post_ids) / $posts_per_page);
  }

  // Find index to start returning post IDs based off current page and posts per page.
  $array_start = ($paged - 1) * $posts_per_page;

  // Find index to stop returning post IDs based off current page and posts per page.
  $array_end = ($paged) * $posts_per_page;

  // Create an empty array to fill with post IDs from the current page
  $current_posts = [];

  // For each post in between the start and end index...
  for ($i = $array_start; $i < $array_end; $i++) {
    // If the current index is higher than posts available...
    if ($i >= count($post_ids)) {
      // Break out of the for loop
      break;
    }

    // Add this post ID to the list of current post IDs
    $current_posts[] = $post_ids[$i];
  }

  // Return the list of current post IDs
  return $current_posts;
}

//Get the string from the meta by accessing the [0]th property in it.
$value = get_post_meta(get_the_ID(),'value_gallery',false)[0];

//Turn it into an array of IDs
$values = explode(",",$value); 

//Get the current page number from query var 'page', or if paged is not set - use 1.
$paged = max( 1, get_query_var( 'page' ) ); 

// Declare how many posts per page you would like
$posts_per_page = 4; 

// Get a list of post IDs that would be on this page.
$res = wpse_52588027_paginated_post_ids($posts_per_page, $paged, $values); 

// If there are posts
  if ( count($res) > 0 ) { 

  // For each post
    foreach ( $res as $image ) { 

  // Echo the post
      echo wp_get_attachment_image( $image );
    }

  // Echo pagination.
    echo paginate_links( array( 
      'base'         => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ), // Set the base for the page links
      'total'        => ceil(count($values) / $posts_per_page), // Get max amount of pages from the WP_Query
      'current'      => $paged, // Use the current page number in pagination as well
      'format'       => '?paged=%#%', // Set the format 
    ) );
  } else { // If there are no posts
    echo "not found"; // Echo "not found"
  }

答案 1 :(得分:1)

尝试此JavaScript分页会更容易。

<div id="gallery_items" class="row">  <!-- gallery div -->
<?php
$gallery_value = get_post_meta(get_the_ID(), 'value_gallery', false)[0];
$split_images = explode(",", $gallery_value); 

$imgcnt = 0;
$hideclass = '';
foreach ( $split_images as $image ) { 
    $imgcnt++;
    if($imgcnt > 4) $hideclass = ' hidden'; //hide divs greater than 4, even though pagination script handles this
    echo "<div class='col-lg-4$hideclass'>".wp_get_attachment_image($image,"cherry-thumb-a") ."</div>";
}
?>
</div>
<div id="page_navigation"></div> <!-- pagination div -->

添加此JS(分页脚本功劳归于Karpov Systems)。

/* * * * * * * * * * * * * * * * *
* Pagination Function
* * * * * * * * * * * * * * * * */
var Pagination = {

    code: '',

    // converting initialize data
    Extend: function(data) {
        data = data || {};
        Pagination.size = data.size || 300;
        Pagination.page = data.page || 1;
        Pagination.step = data.step || 3;
    },

    // add pages by number (from [s] to [f])
    Add: function(s, f) {
        for (var i = s; i < f; i++) {
            Pagination.code += '<a>' + i + '</a>';
        }
    },

    // add last page with separator
    Last: function() {
        Pagination.code += '<i>...</i><a>' + Pagination.size + '</a>';
    },

    // add first page with separator
    First: function() {
        Pagination.code += '<a>1</a><i>...</i>';
    },

    // change page
    Click: function() {
        Pagination.page = +this.innerHTML;
        Pagination.Start();
    },

    // previous page
    Prev: function() {
        Pagination.page--;
        if (Pagination.page < 1) {
            Pagination.page = 1;
        }
        Pagination.Start();
    },

    // next page
    Next: function() {
        Pagination.page++;
        if (Pagination.page > Pagination.size) {
            Pagination.page = Pagination.size;
        }
        Pagination.Start();
    },

    // binding pages
    Bind: function() {
        var a = Pagination.e.getElementsByTagName('a');
        for (var i = 0; i < a.length; i++) {
            if (+a[i].innerHTML === Pagination.page) a[i].className = 'current';
            a[i].addEventListener('click', Pagination.Click, false);
        }
    },

    // write pagination
    Finish: function() {
        Pagination.e.innerHTML = Pagination.code;
        Pagination.code = '';
        Pagination.Bind();
    },

    // find pagination type
    Start: function() {
        goToPage(Pagination.page-1);
        if (Pagination.size < Pagination.step * 2 + 6) {
            Pagination.Add(1, Pagination.size + 1);
        }
        else if (Pagination.page < Pagination.step * 2 + 1) {
            Pagination.Add(1, Pagination.step * 2 + 4);
            Pagination.Last();
        }
        else if (Pagination.page > Pagination.size - Pagination.step * 2) {
            Pagination.First();
            Pagination.Add(Pagination.size - Pagination.step * 2 - 2, Pagination.size + 1);
        }
        else {
            Pagination.First();
            Pagination.Add(Pagination.page - Pagination.step, Pagination.page + Pagination.step + 1);
            Pagination.Last();
        }
        Pagination.Finish();
    },

    // binding buttons
    Buttons: function(e) {
        var nav = e.getElementsByTagName('a');
        nav[0].addEventListener('click', Pagination.Prev, false);
        nav[1].addEventListener('click', Pagination.Next, false);
    },

    // create skeleton
    Create: function(e) {

        var html = [
            '<a>&#9668;</a>', // previous button
            '<span></span>',  // pagination container
            '<a>&#9658;</a>'  // next button
        ];

        e.innerHTML = html.join('');
        Pagination.e = e.getElementsByTagName('span')[0];
        Pagination.Buttons(e);
    },

    // init
    Init: function(e, data) {
        Pagination.Extend(data);
        Pagination.Create(e);
        Pagination.Start();
    }
};

/* * * * * * * * * * * * * * * * *
* Other Functions
* * * * * * * * * * * * * * * * */

var show_per_page = 4;
function showPagination() {
    //getting the amount of elements inside content div
    var number_of_items = jQuery('#gallery_items .col-lg-4').length;
    //calculate the number of pages we are going to have
    var number_of_pages = Math.ceil(number_of_items/show_per_page);

    if(eval(number_of_pages)>1) {
        //set the value of our hidden input fields
        var pg=1;
        Pagination.Init(document.getElementById('page_navigation'), {
            size: number_of_pages, // pages size
            page: pg,  // selected page
            step: 2   // pages before and after current
        });

        //hide all the elements inside content div
        jQuery('#gallery_items .col-lg-4').css('display', 'none');

        //and show the first n (show_per_page) elements
        jQuery('#gallery_items .col-lg-4').slice(0, show_per_page).css('display', 'block');
    }
    else {
        if(eval(number_of_items)>0) {
            jQuery('#gallery_items .col-lg-4').css('display', 'block');
            jQuery('#page_navigation').html('');
        }
        else
            jQuery('#page_navigation').html('<p class="red_font">No Images.</p>');
    }
};

function goToPage(page_num) {
    //get the element number where to start the slice from
    start_from = page_num * show_per_page;

    //get the element number where to end the slice
    end_on = start_from + show_per_page;

    //hide all children elements of content div, get specific items and show them
    jQuery('#gallery_items .col-lg-4').css('display', 'none').slice(start_from, end_on).css('display', 'block');

    //remove previous active & add active to current
    jQuery('#page_navigation .page_link').removeClass('active_page');
    jQuery('.page_link[longdesc=' + page_num +']').addClass('active_page');

    //scroll to top
    jQuery('html, body').animate({
        scrollTop: eval(jQuery("#gallery_items").offset().top)-50
    }, 750);
}

jQuery(document).ready(function(){
    showPagination();
});

希望这可以解决您的问题。

答案 2 :(得分:0)

据我了解,您只想在页面上显示前4张图像。我将要做的是限制foreach。例如,这将是php代码

$value = get_post_meta(get_the_ID(),'value_gallery',false); 
$counter = 0; //initialize counter to 0
foreach ($value as $key ) {
  $values = explode(",",$key);
  $counter++;
  if($counter == 5) //check if counter is 5 one more than we want. If it is then we are going...
     break;         //...to stop the reason this works is because we haven't gotten to your other foreach loop in which it addes another image. 
  foreach ($values as $keys) {
     $args = array(
        'meta_key' => 'value_gallery',
        'meta_value' => $keys,
        'post_per_page' => 4
     );
     $res =  new WP_Query($args);
     if ($res->have_posts()) {
       $id = get_the_ID();
       echo $key;
     }else{
       echo "not found";
     }
  }
 }

如果这不是您要查找的内容,您可以更具体吗?