Error in paging with custom post type

Asked

Viewed 317 times

0

I have two Custom post type created, one for movies and one for series, I have a loop that shows both on index, only when I use paging, it doesn’t work.

Ex. Push to go to/page/2 Only I get a 404 error, as if there was no page 2.

Looking at github and OS forums I found a possible solution, when I add this function in functions.php and some error, only when I go to page 2, the same post appears in the /page/2

add_filter( 'request' , 'pagination_request_filter' );

function pagination_request_filter( $query ) {

    // https://wpquestions.com/Trouble_with_custom_post_type_pagination/937

    if ( empty( $query['preview'] ) && empty( $query['feed'] ) ) {
        $my_post_type = $query['post_type'];
        if ( empty( $my_post_type ) ) {
            $query['post_type'] = 'any';
        }
    }
    return $query;
}

My loop I am using on index and this, I am not using any plugin for paging, I tried to use wp-pagenavi but without success.

I’ll leave the complete code:

<ol id="posts" class="posts">
<?php $args = array('post_type'=>array('filmes', 'series')); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php   if (has_post_thumbnail()) {
$imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'home');
$imgsrc = $imgsrc[0];
} elseif ($postimages = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0")) {
foreach($postimages as $postimage) {
$imgsrc = wp_get_attachment_image_src($postimage->ID, 'home');
$imgsrc = $imgsrc[0];
}
} elseif (preg_match('/
<img [^>]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
$imgsrc = $match[1];
} else {
$imgsrc = get_template_directory_uri() . '/images/no-imagen.png';
} ?>
<li class="post_container" id="post-<?php the_ID(); ?>">
<div class="post post_full">
<div class="post_avatar post-avatar--sticky">
<div class="post_avatar_wrapper">
<?php $id = get_the_author_meta( 'ID' );
if (is_user_online($id) ) {
echo '<span class="tag-status tag-status-online"></span>';
} else {
echo '<span class="tag-status tag-status-offline"></span>';
}
?>
<a class="post_avatar_link">
<div class="post_avatar_image"><?php echo get_avatar( get_the_author_email(), '64' ); ?></div>
</a>

<div class="post_avatar_desc">
<div class="tooltipped tooltipped-n tooltipped-multiline" aria-label="<?php the_author_meta('description'); ?>" style="position: relative;">
<i class="far fa-info-circle"></i>
</div>
<span class="tooltipped tooltipped-n qpost-cont" aria-label="Autor de <?php the_author_posts() ?> postagens"><?php the_author_posts() ?></span>
<span class="qpost-desc">Postagens</span>
<em class="userBanner <?php echo get_author_role(); ?>">
<span class="before <?php echo get_author_role(); ?>"></span>
<strong class="tooltipped tooltipped-n befafter" aria-label="<?php echo get_author_role(); ?>"><?php echo get_author_role(); ?></strong>
<span class="after <?php echo get_author_role(); ?>"></span>
</em>
</div>

</div>
</div>
<div class="post_wrapper">
<div class="post_header">
<div class="post_info">
<div class="post_info_fence">
<a class="post_info_link"><?php the_author(); ?></a>
<span class="reblog_source">
<i class="fas fa-badge-check" style="color: #4FC3F7;"></i>
<a class="post_info_link tooltipped tooltipped-n" aria-label="Atualizado há <?php echo meks_time_ago(); ?> - <?php if(function_exists('the_views')) { the_views(); } ?>">Adicionado há <?php echo meks_time_ago(); ?></a>
</span>
</div>
<div class="post_action_wrapper"><?php if($values= get_post_custom_values( '_audio_video')) { ?><?php echo $values[0]; ?><?php } ?></div>
</div>
</div>
<div class="post_content">
<div class="post_media">
<div class="flipcard">
<div class="flipcard_front">
<div class="flipcard_content">
<div class="poster">
<img src="<?php echo $imgsrc; $imgsrc = ''; ?>" alt="<?php the_title(); ?>"></div>
<div class="description">
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<div class="tag"><?php echo get_the_term_list($post->ID, 'categoria', '', ', ', ''); ?></div>
<div class="sinopse"><?php if($values = get_post_custom_values("_sinopse")) { ?><?php echo $values[0]; ?><?php } ?></div>
<span class="description_post">
<ul class="datasheet_post">
<li>
<span class="datasheet_post_elenco">Elenco:</span>
<?php if(get_the_term_list($post->ID, 'personalidade', '', ', ', '')) { ?>
<span>
<?php echo get_the_term_list($post->ID, 'personalidade', '', ', ', ''); ?>
</span>
<?php } ?>
</li>
<li>
<span class="datasheet_post_criador">Criador:</span>
<?php if(get_the_term_list($post->ID, 'criador', '', ', ', '')) { ?>
<span>
<?php echo get_the_term_list($post->ID, 'criador', '', ', ', ''); ?>
</span>
<?php } ?>
</li>
<li>
<span class="datasheet_post_genero">Gênero:</span>
<?php if(get_the_term_list($post->ID, 'genero', '', ', ', '')) { ?>
<span>
<?php echo get_the_term_list($post->ID, 'genero', '', ', ', ''); ?>
</span>
<?php } ?>
</li>
<li>
<span class="datasheet_post_duracao"">Duração:</span>
<?php if($values= get_post_custom_values( '_runtime')) { ?>
<span>
<?php echo $values[0]; ?>
</span>
<?php } ?>
<span class="date_publication">Publicado em <?php the_time(get_option('date_format')); ?></span>
</li>
</ul>
</span>
<span class="imdb_post_cont">
<div class="imdb_post_data">
<a href="https://www.imdb.com/title/<?php if($values= get_post_custom_values( '_imdb_id')) { ?><?php echo $values[0]; ?><?php } ?>" target="_blank">
<div class="imdb_post_float">
<span class="imdb_post_background"><?php if($values= get_post_custom_values( '_imdb_points')) { ?><?php echo $values[0]; ?><?php } ?></span> </div>
</a>
<div class="imdb_post_rating">
<div class="imdb_post_rating_sub">
<span class="imdb_post_rating_p" style="width: <?php if($values= get_post_custom_values( '_imdb_percentage')) { ?><?php echo $values[0]; ?><?php } ?>;">
</span>
</div>
<span class="imdb_post_dp">
<a class="imdb_post_imdb_a" href="https://www.imdb.com/title/<?php if($values= get_post_custom_values( '_imdb_id')) { ?><?php echo $values[0]; ?><?php } ?>" rel="nofollow" target="_blank">IMDB:</a>
<b class="imdb_post_imdb_b"><?php if($values= get_post_custom_values( '_imdb_points')) { ?><?php echo $values[0]; ?><?php } ?>/10</b>
<b class="imdb_post_imdb_b"><?php if($values= get_post_custom_values( '_imdb_votes')) { ?><?php echo $values[0]; ?><?php } ?></b>
<b class="imdb_post_imdb_b">votos</b>
</span>
</div>
</div>
<div class="parental_rating_description">
<div class="tooltipped tooltipped-nw content_parental content_parental_rating-<?php if($values= get_post_custom_values( '_classification')) { ?><?php echo $values[0]; ?><?php } ?>" aria-label="<?php if($values= get_post_custom_values( '_description')) { ?><?php echo $values[0]; ?><?php } ?>"><?php if($values= get_post_custom_values( '_classification')) { ?><?php echo $values[0]; ?><?php } ?></div>
</div>
</span>
</div>
</div>
</div>
</div>
</div>

</div>
<div class="post_footer">
<a class="update tooltipped tooltipped-s" aria-label="Atualizado em <?php the_modified_date ('d \d\e F \d\e Y'); ?>">Atualizado em <?php the_modified_date ('d \d\e F \d\e Y'); ?></a>
<a class="download" href="<?php the_permalink() ?>">Mais Informações</a></div>
</div>
</div>
</li>
<?php $activar_ads = get_option('activar-slider-footer'); if ($activar_ads == "true") { ?>
<?php $random = rand(1,6); if ($ads2 == 3) : ?>
<?php $ads = get_option('slider-footer'); if (!empty($ads)) echo stripslashes(get_option('slider-footer')); ?>
<?php endif; $ads2++; ?>
<?php } ?>

<?php endwhile; wp_reset_query(); ?>
<?php else : ?>
<div class="no_principal">
<?php _e('No content available', 'mundothemes'); ?>
</div>
<?php endif; ?>
<?php pagination(); ?>
</ol>

My function of paging:

function pagination($pages = '', $range = 2) { 
    $pagn = ($range * 2)+1;
    global $paged; if(empty($paged)) $paged = 1;
    if($pages == '') {
        global $wp_query; $pages = $wp_query->max_num_pages; 
        if(!$pages){ $pages = 1; } 
    }
    if(1 != $pages) { 
        echo "<div class='paginado'><ul>";

        if($paged > 2 && $paged > $range+1 && $pagn < $pages) 
            echo "<li><a class=previouspostslink' rel='nofollow' href='".get_pagenum_link(1)."'>".__( 'First', 'mundothemes' )."</a></li>"; 
        if($paged > 1 && $pagn < $pages) 
            echo "";
        for ($i=1; $i <= $pages; $i++){ 
            if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $pagn )) { 
                echo ($paged == $i)? "<li class='dd'><a class='current'>".$i."</a></li>":"<li><a rel='nofollow' class='page larger' href='".get_pagenum_link($i)."'>".$i."</a></li>";
            } 
        } 
        if ($paged < $pages && $pagn < $pages) 

        if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $pagn < $pages) 
            echo "<li><a rel='nofollow' class=previouspostslink' href='".get_pagenum_link($pages)."'>".__( 'Last', 'mundothemes' )."</a></li>";
            echo "</ul></div>"; 
    }
}

1 answer

0

After two days searching for information and methods to fix this error, I finally found a way.

I was almost giving up, I decided I came here last case to ask, usually always have the people who know more about the subject, however I ended up solving "alone"...

First of all I’m going to say that I’m not a programmer, I’m just a curious who usually gets it right whenever I want to do something rs, so I have no idea how to explain the functions, but I know it worked for me like this.

Loop (I think that’s it) that I use to request the posts that are on my custom post type:

<?php $args = array('post_type'=>array('filmes', 'series'),'paged' => $paged,'orderby'=>'date','posts_per_page' => 2); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

In the above request I want to show all posts that are in my custom post type, which are "movies" and "series", where this written "'posts_per_page' => 2" and the amount of post that will be displayed in the index, which in my case is only 2.

These are my two custom post type:

Custom Post Type

The function of custom post type "movies" and "series":

add_action( 'init', 'post_type_movies' );

function post_type_movies() {

  $labels = array(
    'name'                => __( 'Filme' ),
    'singular_name'       => __( 'Filmes' ),
    'add_new'             => __( 'Adicionar Novo' ),
    'add_new_item'        => __( 'Adicionar Novo Filme' ),
    'edit_item'           => __( 'Editar Filme' ),
    'new_item'            => __( 'Novo Filme' ),
    'all_items'           => __( 'Todos os Filmes' ),
    'view_item'           => __( 'Ver Filme' ),
    'search_items'        => __( 'Pesquisar Filme' ),
    'not_found'           => __( 'Nenhum filme encontrado' ),
    'not_found_in_trash'  => __( 'Nenhum filme na lixeira' ),
    'menu_name'           => __( 'Filmes' ),
  );

  $supports = array( 'title', 'editor', 'thumbnail', 'comments');

  $slug = get_theme_mod( 'movies_permalink' );
  $slug = ( empty( $slug ) ) ? 'filmes' : $slug;

  $args = array(
    'labels'              => $labels,
    'public'              => true,
    'publicly_queryable'  => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'query_var'           => true,
    //'rewrite'             => array( 'slug' => $slug ,'with_front' => false),
    'rewrite'             => array( 'slug' => $slug ),
    'capability_type'     => 'post',
    'has_archive'         => true,
    'hierarchical'        => false,
    'menu_position'       => 4,
    'supports'            => $supports,
    'menu_icon'           => 'dashicons-editor-video',
  );
  $wp_query = new WP_Query($args);
  $posts = $wp_query->posts;

  register_post_type( 'filmes', $args );

}

add_action( 'init', 'post_type_series' );

function post_type_series() {

  $labels = array(
    'name'                => __( 'Série' ),
    'singular_name'       => __( 'Séries' ),
    'add_new'             => __( 'Adicionar Novo' ),
    'add_new_item'        => __( 'Adicionar Nova Série' ),
    'edit_item'           => __( 'Editar Série' ),
    'new_item'            => __( 'Nova Série' ),
    'all_items'           => __( 'Todas as Séries' ),
    'view_item'           => __( 'Ver Série' ),
    'search_items'        => __( 'Pesquisar Série' ),
    'not_found'           => __( 'Nenhuma série encontrado' ),
    'not_found_in_trash'  => __( 'Nenhuma série na lixeira' ),
    'menu_name'           => __( 'Séries' ),
  );

  $supports = array( 'title', 'editor', 'thumbnail', 'comments');

  $slug = get_theme_mod( 'series_permalink' );
  $slug = ( empty( $slug ) ) ? 'series' : $slug;

  $args = array(
    'labels'              => $labels,
    'public'              => true,
    'publicly_queryable'  => true,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'query_var'           => true,
    //'rewrite'             => array( 'slug' => $slug ,'with_front' => false),
    'rewrite'             => array( 'slug' => $slug ),
    'capability_type'     => 'post',
    'has_archive'         => true,
    'hierarchical'        => false,
    'menu_position'       => 4,
    'supports'            => $supports,
    'menu_icon'           => 'dashicons-editor-video',
  );
  $wp_query = new WP_Query($args);
  $posts = $wp_query->posts;

  register_post_type( 'series', $args );

}

Here is a filter I don’t know for sure what it does, but this in my functions.php file, this with some remarks I put to my understanding:

add_filter( 'request' , 'pagination_request_filter' );

function pagination_request_filter( $query ) {
    // https://wpquestions.com/Trouble_with_custom_post_type_pagination/937
    // https://codex.wordpress.org/Class_Reference/WP_Query
    if ( empty( $query['preview'] ) && empty( $query['feed'] ) ) {
        $my_post_type = $query['post_type'];
        if ( empty( $my_post_type ) ) {
            //$query['post_type'] = 'any';
            $query['post_type'] = array( 'filmes', 'series');
            //< ?php $args = array('post_type'=>array('filmes', 'series'),'paged' => $paged,'orderby'=>'date','posts_per_page' => 2); query_posts($args); if ( have_posts() ) : while ( have_posts() ) : the_post(); ? >
            //< ?php $paged = (get_query_var('paged')) ? get_query_var('paged'):1; query_posts(array('post_type' =>array('filmes', 'series'), 'paged' => $paged, 'orderby'=>'date','posts_per_page' => 2)); if ( have_posts() ) : while ( have_posts() ) : the_post(); ? >
            // Os dois codigos funcionam, não se esquecer de deixar em: 1 post nas Configurações de leitura
        }
    }
    return $query;
}

I tested with the wp-pagenavi plugin and it worked, but if you don’t want to use any plugin just add the function below in your functions.php:

function post_pagination($pages = '', $range = 4) {  
    $showitems = ($range * 2)+1;  

    global $paged;
    if(empty($paged)) $paged = 1;

    if($pages == '')
    {
        global $wp_query;
        $pages = $wp_query->max_num_pages;
        if(!$pages)
        {
            $pages = 1;
        }
    }   

    if(1 != $pages)
    {
         //echo "<div class='paginacao'><span class='especial'>P&aacute;ginas</span>";
        echo "<div class='paginacao'>";
        if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."' class='current'>&laquo;</a>";
        if($paged > 6 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>1</a> <span class='current'>...</span>";

        for ($i=1; $i <= $pages; $i++)
        {
            if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
            {
                echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a>";
            }
        }

        if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<span class='current'>...</span> <a href='".get_pagenum_link($pages)."'>$pages</a>";
        if ($paged < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($paged + 1)."' class='current'>&raquo;</a>"; 
        echo "</div>";
    }
}

Add at the end of the index after "endif;" in mine after endif:

<?php post_pagination();?>

So far I found no problem, at least with me working smooth, if anyone has any suggestions on how to improve the function or any better method, just comment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.