Как я могу показать изображения с нумерацией страниц, используя массив идентификаторов изображений с Wordpress? - PullRequest
0 голосов
/ 01 октября 2018

Отредактировано: у меня есть код, этот код показывает meta_post и с meta_post я покажу изображение с wp_get_attachment_image, каждый пост имеет массив value_gallery в 1, а значение массива id-attr image,1 value_gallery имеют 2 или более id-attr, разделенных запятой, поэтому я хочу сделать пост постраничный, но я не знаю, как это сделать, я был сделать этот код на single-gallery.php,

я хочу сделать этокод вроде this , но этот код по-прежнему просто показывает «not found», если кто-нибудь может мне помочь, я буду очень рад

note: значение meta_value value_gallery - это массив ex:array(1) { [0]=> string(29) "1402,1435,1398,1434,1434,1434" } спасибо за ваше внимание

Отредактировано: из этого кода я пытаюсь показать meta_post на страницу (например: 4 на страницу) и пытаюсь сделать нумерацию страниц, обновленный код:

$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;

updated 2 Я объясню еще раз с этим вопросом, поэтому я пытаюсь сделать пост в галерее, пост в галерее имеет meta_post, значение которого равно 1 массиву, например: array(1) { [0]=> string(29) "1402,1435,1398,1434,1434,1434" }, поэтому это значение составляет id-attr изображения, и я попытаюсь сделать нумерацию страниц для this meta_post

обновлено 3 это иллюстрация того, что я пытаюсь сделать с этим кодом pagination post_meta

Ответы [ 3 ]

0 голосов
/ 09 октября 2018

Если вы хотите получать сообщения по массиву их идентификаторов, вы можете использовать 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 содержит повторяющиеся идентификаторы, 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"
  }
0 голосов
/ 09 октября 2018

Попробуйте эту 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();
});

Надеюсь, что это решит вашу проблему.

0 голосов
/ 09 октября 2018

Насколько я понимаю, вы хотите отобразить только первые 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";
     }
  }
 }

Если это не то, что вы ищете, можете ли вы быть более конкретным?

...