Как сделать пагинацию с кастомным Loop?

Я использую пользовательский цикл для отображения флеш игры. Я хочу сделать пагинацию на страницах игр по категориям. category.php:

<?php
if ($cat)
{
$cols = 2;
$rows = 4;
$paged = (('paged')) ? get_query_var('paged') : 1;
$post_per_page = $cols * $rows; // -1 shows all posts
$do_not_show_stickies = 1; // 0 to show stickies

$args = array(
    'post_type' => 'game',
    'category__in' => array($cat),
    'orderby' => 'date',
    'order' => 'DESC',
    'paged' => $paged,
    'posts_per_page' => $post_per_page,
    'caller_get_posts' => $do_not_show_stickies
);
$wp_query = new WP_Query($args); 
begin_roundblock(get_cat_name($cat), 'games-pages-category', null);
if (have_posts()):
  echo '<div class="games-list-block-content">';
    /* Begin Breadcrump*/
    echo '<div class="breadcrumb">';
            if(function_exists('bcn_display'))
            {
                echo '<div class="breadcrumb-text">';
                echo 'Go Back:';
                    bcn_display();
                echo '</div>';
            }
    echo '</div>';
    /* End Breadcrump*/
    $i = 0;
    while (have_posts())
    {
        the_post();

        $class = 'game-info';
        if ($i % $cols == 0)
            $class .= ' clear';

        echo '<div class="'.$class.'"><a href="'.get_permalink().'">';
        the_post_thumbnail(array(60, 60), array('class' => 'game-icon'));
        $title = get_the_title();
        if (mb_strlen($title) > 7)
            $title = mb_substr($title, 0, 6).'...';
        echo '<span class="game-title">'.$title.'</span></a></div>';
        $i++;
    } ?>
     <div class="navigation clear game-info-last-row">
<?php if(function_exists('wp_pagenavi')) 
          { wp_pagenavi(); } ?>
</div>
//For default WP
 <div class="navigation">
  <div class="alignleft"><?php next_posts_link('« Older Entries') ?></div>
  <div class="alignright"><?php previous_posts_link('Newer Entries »') ?></div>
</div>

  </div>
<?php else: ?>
    <h2 class="center">Not Found</h2>
    <p class="center">Sorry, but you are looking for something that isnt here.</p>
    <?php get_search_form(); ?>
<?php endif;
end_roundblock();
}
?>

Я получил ссылки на страницы, также я попытался использовать плагин wp-pagenavi, так как нужно рассчитать количество постов (игр) для отображения с нужным количеством страниц. Но когда я нажал на ссылку «Старые записи» (или любую страницу в случае плагина pagenavi), он перешел на главную страницу, а URL-адрес был «http://mydomain/category/category_name/page/2». Я пытаюсь использовать много других плагинов, но все же. Кто-нибудь может мне помочь с этим?

Благодарю.

Понравилась статья? Поделиться с друзьями:
WPAsk
Ответов: 13
  1. Jan Fabry

    @glazsasha: Am I correct when I think you display this on a regular page? (The is_page() at the top?) So you have a page /the-history-of-arcade-games/, meta cat value is 2 (for arcade games), and you want to display (in a sidebar, or at the bottom) 4 posts from this category? In this case, should the next page link go to /the-history-of-arcade-games/page/2/, or /category/arcade/page/2/? Because the former is (by default) not supported by WordPress.

  2. Jan Fabry

    If this is the main loop you use to display posts on your page, you should not execute a new loop but modify the existing loop that WordPress will execute anyway. This way you can be sure that all extra query parameters will be taken into account.

    Here we want to display posts of type game and limit the number of posts on the page. You can do this with the following code:

    add_action( 'pre_get_posts', 'wpse5477_pre_get_posts' );
    function wpse5477_pre_get_posts( &$wp_query )
    {
        if ( $wp_query->is_category() ) {
            $wp_query->set( 'post_type', 'game' );
            $wp_query->set( 'posts_per_page', 2 );
        }
    }
    
    1. glazsasha

      What should I do, if I want to display (for example) 5 posts from certain category on the main page? By this function we already determined post_per_page = 2 for posts from category. How could I achieve to display 2 post from certain category on the page category.php and 5 posts from the same category on the main page. Does anybody has some idea? @Jan Fabry, I want to ask in the chat room for this questions, but the room was frozen.

    2. Jan Fabry

      Я думаю, что это разные вопросы. Вы говорите о домашней странице или первой странице архива категорий?

  3. Steven

    Похоже, вы используете wp-pagenavi от Lester Chan?

    Тогда просто сделайте это:

    $page = (get_query_var('paged')) ? get_query_var('paged') : 1; // U don't need this for normal WP paging.
    
     if(function_exists('wp_pagenavi')) 
                  { wp_pagenavi(); }
    

    В противном случае вы можете использовать встроенную пагинацию:

    <div class="navigation">
      <span class="floatLeft"><?php next_posts_link('&laquo; Older Entries') ?></span>
      <span class="floatRight"><?php previous_posts_link('Newer Entries &raquo;') ?></span><div class="clear"></div>
    </div> 
    
    1. glazsasha

      You're lucky! Lester Chan plugin can't help in my case. Now, I think maybe the problem is that i'm trying to use pagination for page games by category or there is no different?

    2. glazsasha

      Yes, I try to use wp-pagenavi from Lester Chan and do this way in case of default WP paging. Sorry, but I think the different in name's of class(class="floatLeft,class="floatRight) and &raquo;&laquo; don't resolve my promlem. As I wrote in my code: <div class="navigation"> <div class="alignleft"><?php next_posts_link('« Older Entries') ?></div> <div class="alignright"><?php previous_posts_link('Newer Entries »') ?></div> </div> But thanks anyway!

    3. Steven

      <span class="floatLeft"> — это всего лишь класс CSS, который я использую для текста слева. Вы можете использовать все, что вы хотите. Это не имеет никакого отношения к пагинации.

    4. Steven

      Да… на самом деле, у меня та же проблема, что и у вас. Я могу перейти на следующую страницу, но те же статьи перечислены. Это работает, если используется плагин LEsetr Chan.

  4. Jan Fabry

    Извините, но я не думаю, что понимаю ваш вопрос. Это код только для боковой панели или для всей страницы? Что вы хотите показать на второй странице? Каким должен быть URL первой и второй страницы?

  5. glazsasha

    На самом деле, я написал этот код просто для отображения моего пользовательского цикла (с ‘post_type’ => ‘game’). Извините, если я ввел вас в заблуждение. Теперь я удалил is_page() из кода, это моя вина, извините. Просто чтобы быть ясно: у меня есть блок боковой панели с названием категории игр на главной странице. Затем я нажал на любую категорию, и URL-адрес выглядит так: mydomain/category/category_name. Я вижу игру из этой категории, когда я нажимаю на любую страницу (плагин Lester Chan) или «Старые записи» (WP по умолчанию), она переходит в mydomain/category/category_name/page/2. В этом и есть проблема.

  6. glazsasha

    Я мог бы применить определенный код, который я использовал. Но я думаю, что нет никакой разницы, как отображать список игр и для какой-то категории.

  7. Jan Fabry

    Возможно, будет понятнее, если вы включите полный код из файла шаблона и сообщите нам, какой это файл (archive.php, category.php,…).

Добавить ответ

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: