Pagination with custom filtering Wordpress - php

When creating custom filtering based on ACF fields, pagination stopped working. That is, it works, but when the filter is applied, it does not update the pagination of articles, but uses the pagination as if all articles were displayed. I have already tried the standard pagination options
<?php
$free = $_COOKIE['free_article_val'];
$block = $_COOKIE['block_article_val'];
$bought = $_COOKIE['bought_article_val'];
$args = array(
'posts_per_page' => 5,
'paged' => get_query_var('paged') ?: 1
);
$query = new WP_Query($args);
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
$its_free_post_value = PostFilter::Its_free_post();
$bought_post = PostFilter::Its_bought_post();
if ($its_free_post_value == 1 && $free !== 'true_val' && $_SESSION['start_session_val'] == 1){
continue;
}
if ($bought_post == 1 && $bought !== 'true_val' && $_SESSION['start_session_val'] == 1){
continue;
}
if ($bought_post == 2 && $block !== 'true_val' && $_SESSION['start_session_val'] == 1){
continue;
}
biagiotti_mikado_get_post_format_html( $blog_type );
}
wp_reset_postdata(); // сбрасываем переменную $post
}else{
biagiotti_mikado_get_module_template_part( 'templates/parts/no-posts', 'blog' );
}
?>
</div>
<?php
previous_posts_link( 'Prev page ' );
next_posts_link( ' Next page', $query->max_num_pages );
PostFilter::Check_session(); ?>```

To start with as step 1, this is incorrect
'paged' => get_query_var('paged') ?: 1
I would replace it with
'paged' => ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

Related

Wordpress post offset is affecting admin area

I'm trying to get a post offset to work on category and tag archives with a couple of category exclusions.
I have 3 functions. The first creats a custom loop which is inserted via shortcode and contains 3 posts, and the other two functions offset the main query by 3 and fix the pagination as per this codex article
It seems to work where it should, except it's also offsetting posts in the backend admin area for all post types and I can't work out how to stop that happening.
For clarity, posts should be offset by 3 on category and tag archives only, excluding the categories added to the array.
function archive_loop_shortcode() {
$current_archive = get_queried_object();
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
'tax_query' => array(
array(
'taxonomy' => $current_archive->taxonomy,
'field' => 'term_id',
'terms' => $current_archive->term_id,
),
),
);
$archive_query = null;
$archive_query = new WP_query($args);
echo '<div class="kb-custom-archive-loop"><div class="kb-custom-archive-loop-inner">';
if($archive_query->have_posts()):
while($archive_query->have_posts()) : $archive_query->the_post();
$custom = get_post_custom( get_the_ID() );
echo '<article>';
echo '<figure><div>' . get_the_post_thumbnail() . '</div></figure>';
echo '<h2>' . get_the_title() . '</h2>';
echo '</article>';
endwhile;
wp_reset_postdata();
else :
_e( 'Sorry, no posts matched your criteria.' );
endif;
echo "</div></div>";
}
add_shortcode( 'archive_loop', 'archive_loop_shortcode' );
add_action('pre_get_posts', 'myprefix_query_offset', 1 );
function myprefix_query_offset(&$query) {
if ( ! is_admin() && ! is_home() && ! is_search() && ! is_author() && ! $query->is_main_query() ) {
if ( ! is_category(array('28770','28688')) || is_tag() ) {
return;
}
}
$offset = 3;
$ppp = get_option('posts_per_page');
if ( $query->is_paged ) {
$page_offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );
$query->set('offset', $page_offset );
}
else {
$query->set('offset',$offset);
}
}
add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
function myprefix_adjust_offset_pagination($found_posts, $query) {
$offset = 3;
if ( ! is_admin() && ! is_home() && ! is_search() && ! is_author() && ! $query->is_main_query() ) {
if ( ! is_category(array('28770','28688')) || is_tag() ) {
return $found_posts - $offset;
}
}
return $found_posts;
}

WooCommerce filter admin order list based on added custom header field

In WooCommerce, I have added a new custom column 'Language' in my admin order list with custom values 'Japanese' or 'Non Japanese'.
How should I add filter option for Japanese language and Non Japanese language.
I added a filter drop down using below code:
add_action( 'restrict_manage_posts', 'wpse45436_admin_posts_filter_restrict_manage_posts' );
function wpse45436_admin_posts_filter_restrict_manage_posts(){
global $post_type;
if( $post_type == 'shop_order' ) {
//change this to the list of values you want to show
//in 'label' => 'value' format
$values = array(
'Japanese' => 'Japanese',
'Non Japanese' => 'Non Japanese',
);
?>
<select name="ADMIN_FILTER_FIELD_VALUE">
<option value=""><?php _e('Filter By ', 'wose45436'); ?></option>
<?php
$current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_FIELD_VALUE']:'';
foreach ($values as $label => $value) {
printf (
'<option value="%s"%s>%s</option>',
$value,
$value == $current_v? ' selected="selected"':'',
$label
);
}
?>
</select>
<?php
}
}
I also added some code for filtering order list but its not working, here is my code:
add_action( 'pre_get_posts', 'apply_my_custom_product_filters' );
function apply_my_custom_product_filters( $query ) {
global $pagenow;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ( $query->is_admin && $pagenow == 'edit.php' && isset( $_GET['ADMIN_FILTER_FIELD_VALUE'] ) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '' && $_GET['post_type'] == 'shop_order' ) {
$meta_key_query = array(
array(
'meta_key' => 'order_add_language',
'value' => esc_attr( $_GET['ADMIN_FILTER_FIELD_VALUE'] ),
'compare' => '=',
),
'posts_per_page' => 10,
'paged' => $paged,
);
$query->set( 'meta_query', $meta_key_query );
}
}
There is some errors in your code… Try the following revisited code:
add_action( 'restrict_manage_posts', 'display_admin_shop_order_language_filter' );
function display_admin_shop_order_language_filter(){
global $pagenow, $post_type;
if( 'shop_order' === $post_type && 'edit.php' === $pagenow ) {
$domain = 'woocommerce';
$languages = array( __('Japanese', $domain), __('Non Japanese', $domain) );
$current = isset($_GET['filter_shop_order_language'])? $_GET['filter_shop_order_language'] : '';
echo '<select name="filter_shop_order_language">
<option value="">' . __('Filter By ', $domain) . '</option>';
foreach ( $languages as $value ) {
printf( '<option value="%s"%s>%s</option>', $value,
$value === $current ? '" selected="selected"' : '', $value );
}
echo '</select>';
}
}
add_action( 'pre_get_posts', 'process_admin_shop_order_language_filter' );
function process_admin_shop_order_language_filter( $query ) {
global $pagenow;
if ( $query->is_admin && $pagenow == 'edit.php' && isset( $_GET['filter_shop_order_language'] )
&& $_GET['filter_shop_order_language'] != '' && $_GET['post_type'] == 'shop_order' ) {
$meta_query = $query->get( 'meta_query' ); // Get the current "meta query"
$meta_query[] = array( // Add to "meta query"
'meta_key' => 'order_add_language',
'value' => esc_attr( $_GET['filter_shop_order_language'] ),
);
$query->set( 'meta_query', $meta_query ); // Set the new "meta query"
$query->set( 'posts_per_page', 10 ); // Set "posts per page"
$query->set( 'paged', ( get_query_var('paged') ? get_query_var('paged') : 1 ) ); // Set "paged"
}
}
Code goes in function.php file of your active child theme (or active theme). It should works.
This is wrong in your meta_key_query.You can try this code.
add_action( 'pre_get_posts', 'apply_my_custom_product_filters' );
function apply_my_custom_product_filters( $query ) {
global $pagenow;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ( $query->is_admin && $pagenow == 'edit.php' && isset( $_GET['ADMIN_FILTER_FIELD_VALUE'] ) && $_GET['ADMIN_FILTER_FIELD_VALUE'] != '' && $_GET['post_type'] == 'shop_order' ) {
$meta_key_query = array(
array(
'meta_key' => 'order_add_language',
'value' => esc_attr( $_GET['ADMIN_FILTER_FIELD_VALUE'] ),
)
);
$query->set( 'meta_query', $meta_key_query );
}
}

Wordpress Custom Post type Category View with Pagination

I have a custom post type 'charters' and within my category.php page I have a loop pulling in 'charter' posts for the current category id. I have a custom pagination setup displaying page numbers when I click page 2 link, it goes to URL /page/2 which displays a 404 error. I can't figure out why I am getting the 404. If I adjust my posts per page the pagination updates and displays the correct number of pages but the links do not show up.
Category.php Code:
<?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$product_args = array(
'post_type' => 'charters',
'posts_per_page' => 10, //the same as the parse_query filter in our functions.php file
'paged' => $paged,
'page' => $paged,
'cat' => $cat
);
$product_query = new WP_Query( $product_args ); ?>
<?php if ( $product_query->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $product_query->have_posts() ) : $product_query->the_post(); ?>
<article class="loop">
<h3><?php the_title(); ?></h3>
<div class="content">
<?php the_excerpt(); ?>
</div>
</article>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php
if (function_exists( 'custom_pagination' )) :
custom_pagination( $product_query->max_num_pages,"",$paged );
endif;
?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
Functions.php Code:
function prefix_change_cpt_archive_per_page( $query ) {
//* for cpt or any post type main archive
if ( $query->is_main_query() && ! is_admin() && is_post_type_archive( 'product' ) ) {
$query->set( 'posts_per_page', '10' );
}
}
add_action( 'pre_get_posts', 'prefix_change_cpt_archive_per_page' );
function prefix_change_category_cpt_posts_per_page( $query ) {
if ( $query->is_main_query() && ! is_admin() && is_category( 'test-category' ) ) {
$query->set( 'post_type', array( 'product' ) );
$query->set( 'posts_per_page', '2' );
}
}
add_action( 'pre_get_posts', 'prefix_change_category_cpt_posts_per_page' );
function custom_pagination( $numpages = '', $pagerange = '', $paged='' ) {
if (empty($pagerange)) {
$pagerange = 2;
}
global $paged;
if (empty($paged)) {
$paged = 1;
}
if ($numpages == '') {
global $wp_query;
$numpages = $wp_query->max_num_pages;
if(!$numpages) {
$numpages = 1;
}
}
$pagination_args = array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%',
'total' => $numpages,
'current' => $paged,
'show_all' => False,
'end_size' => 1,
'mid_size' => $pagerange,
'prev_next' => True,
'prev_text' => __('«'),
'next_text' => __('»'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<nav class='custom-pagination'>";
echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> ";
echo $paginate_links;
echo "</nav>";
}
My Permalink Settings are set to "Post Name" I have a feeling this has something to do with rewrites but I can not figure out how to get the page urls to work correctly. An example of my categories are as follows:
/category/long-beach/
/category/san-diego/
you should try this:
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'charters',
'cat'=> $cat,
'post_per_page'=> 6,
'paged' => $paged
);
$my_query = new WP_Query( $args );
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><?php the_title(); ?></p><?php
endwhile;
}
wp_reset_query();
?>
<?php echo pnavigation( $query ); ?>
then you need to add following code to function.php :
function pnavigation( $wp_query ) {
$big = 999999999; // need an unlikely integer
$pages = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'prev_next' => false,
'type' => 'array',
'prev_next' => TRUE,
'prev_text' => '←',
'next_text' => '→',
) );
if( is_array( $pages ) ) {
$paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
echo '<ul class="pagination pagination-lg">';
foreach ( $pages as $page ) {
echo "<li>$page</li>";
}
echo '</ul>';
}
}
you need to just replace url (client-testimonials) with your url
function pagination_rewrite() {
add_rewrite_rule('client-testimonials/page/?([0-9]{1,})/?$', 'index.php?pagename=client-testimonials&paged=$matches[1]', 'top');
}
add_action('init', 'pagination_rewrite');
If you are using default pagination then please use below code.
<?php
$current_page = get_queried_object();
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'charters',
'paged' => $paged,
'cat'=> $cat);
$my_query = new WP_Query( $args );
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<p><?php the_title(); ?></p><?php
endwhile;
}
next_posts_link( 'Older Entries', $my_query->max_num_pages );
previous_posts_link( 'Newer Entries' );
wp_reset_query();
?>
Add below code in your function.php
function posts_on_categorypage( $query ) {
if ( $query->is_category()) {
$query->set( 'posts_per_page', '10' );
}
}
add_action( 'pre_get_posts', 'posts_on_categorypage' );
There was a couple of errors in my code. This is what I get for copy/pasting code and not going through it line by line. Thanks everyone who helped out, but I got this to work by changing:
Bad Code:
function prefix_change_category_cpt_posts_per_page( $query ) {
if ( $query->is_main_query() && ! is_admin() && is_category( 'test-category' ) ) {
$query->set( 'post_type', array( 'product' ) );
$query->set( 'posts_per_page', '2' );
}
}
Good Code:
function prefix_change_category_cpt_posts_per_page( $query ) {
if ( $query->is_main_query() && ! is_admin() && is_category( $cat ) ) {
$query->set( 'post_type', array( 'charters' ) );
$query->set( 'posts_per_page', '10' );
}
}

rel="next" isn't added to head in custom query and page post type

i want a numberic pagination in my custom query. therefor i use this script in my function:
function wpbeginner_numeric_posts_nav() {
if( is_singular() )
return;
global $wp_query;
/** Stop execution if there's only 1 page */
if( $wp_query->max_num_pages <= 1 )
return;
$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
$max = intval( $wp_query->max_num_pages );
/** Add current page to the array */
if ( $paged >= 1 )
$links[] = $paged;
/** Add the pages around the current page to the array */
if ( $paged >= 3 ) {
$links[] = $paged - 1;
$links[] = $paged - 2;
}
if ( ( $paged + 2 ) <= $max ) {
$links[] = $paged + 2;
$links[] = $paged + 1;
}
echo '<div class="navigation"><ul>' . "\n";
/** Previous Post Link */
if ( get_previous_posts_link() ) {
printf( '<li>%s</li>' . "\n", get_previous_posts_link(__('Previous Page','tkh').'') );
add_filter( 'wpseo_prev_rel_link', get_previous_posts_link() );
}
/** Link to first page, plus ellipses if necessary */
if ( ! in_array( 1, $links ) ) {
$class = 1 == $paged ? ' class="active"' : '';
printf( '<li%s>%s</li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );
if ( ! in_array( 2, $links ) )
echo '<li>…</li>';
}
/** Link to current page, plus 2 pages in either direction if necessary */
sort( $links );
foreach ( (array) $links as $link ) {
$class = $paged == $link ? ' class="active"' : '';
printf( '<li%s>%s</li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
}
/** Link to last page, plus ellipses if necessary */
if ( ! in_array( $max, $links ) ) {
if ( ! in_array( $max - 1, $links ) )
echo '<li>…</li>' . "\n";
$class = $paged == $max ? ' class="active"' : '';
printf( '<li%s>%s</li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
}
/** Next Post Link */
if ( get_next_posts_link() )
printf( '<li>%s</li>' . "\n", get_next_posts_link(__('Next Page','tkh').'') );
echo '</ul></div>' . "\n";
}
to add the rel="next" and rel="prev" meta tags i use:
function cor_rel_next_prev_pagination() {
global $wp_query;
$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
//print_r( wp_count_pages() );
if ( get_previous_posts_link() ) { ?>
<link rel="prev" href="<?php echo get_pagenum_link( $paged - 1 ); ?>">
<?php
}
if ( get_next_posts_link('',5) ) { ?>
<link rel="next" href="<?php echo get_pagenum_link( $paged + 1 ); ?>">
<?php
}
}
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
add_action('wp_head', 'cor_rel_next_prev_pagination');
And now my problem: You see in the second script get_next_posts_link('',5). When i write a static numberic (5) into the function it is workly perfectly. But i can't make it work dynamically (e.g. with: $wp_query->max_num_pages). Probably because $wp_query isn't init in the wp_head action. Also i can't use wp_count_posts() because i think it is not working with a post_type page. So mainly: How can't get the working. Andy suggestions?
By the way, here is how i setup the query in my page:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$news_events = array(
'numberposts' => -1,
'post_type' => ['news','event'],
'orderby' => 'date',
//'posts_per_page' => get_option( 'posts_per_page' ),
'posts_per_page' => 1,
'paged' => $paged
);
$wp_query = new WP_Query($news_events);
if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts()) : $wp_query->the_post();
For now i found a solution. but its not perfect. I added in the cor_rel_next_prev_pagination() function this line:
if ( get_post_field( 'post_name', get_post() ) == news_events) $max = ceil( (wp_count_posts('event')->publish + wp_count_posts('news')->publish ) / get_option('posts_per_page') ); else $max = wp_count_posts()->publish / get_option('posts_per_page');
and also in the same function:
if ( get_next_posts_link('', $max ) ) { ?>
but maybe someone got a better solution.

Trying to achieve WP Pagination with only Prev and Next buttons

I'm trying to modify my code for pagination in such a way that it only displays the Prev and Next buttons with no pages in the middle. This is proving to be kind of hard because paginate_links function doesn't have many options in terms of arguments which I can pass to disable the pages from being displayed.
Also using next_posts_link() and previous_posts_link() functions doesn't really help because that links to mydomain.com/page/2 whereas my default homepage is something like this mydomain.com/?fp_type=hot (to display particular kind of custom posts)
This is my pagination code
<?php
global $wp_query;
global $wp_rewrite;
if( is_search() ){
if( (int) get_query_var('page') > 0 ){
$current = get_query_var('page');
}else{
if( (int) get_query_var('paged') > 0 ){
$current = get_query_var('paged');
}else{
$current = 1;
}
}
$wp_query = new WP_Query('paged='. $current . '&s='.get_query_var('s') );
$pagination = array(
'base' => #add_query_arg( 'paged' , '%#%' ),
'format' => '',
'total' => $wp_query -> max_num_pages,
'current' => $current,
'show_all' => false,
'prev_next'=> true,
'prev_text'=> __('« Previous','cosmotheme'),
'next_text'=> __('Next »','cosmotheme'),
'type' => 'array'
);
if( $wp_rewrite->using_permalinks() ){
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 'search', remove_query_arg( 's', get_pagenum_link( 1 ) ) ) ) . 'page/%#%/', 'paged' );
}
if( !empty($wp_query->query_vars['s'] ) ){
$pagination['add_args'] = array( 's' => urlencode( get_query_var( 's' ) ) );
}
$pgn = paginate_links( $pagination );
if( !empty( $pgn ) ){
echo '<div class="pag">';
echo '<ul class="b_pag center p_b">';
if( $current == 1 ){
$current--;
}
foreach($pgn as $k => $link){
print '<li>' . str_replace("'",'"',$link) . '</li>';
}
echo '</ul>';
echo '</div>';
}
}else{
$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
$pagination = array(
'base' => #add_query_arg('paged','%#%'),
'format' => '',
'total' => $wp_query->max_num_pages,
'current' => $current,
'show_all' => false,
'type' => 'array'
);
if( $wp_rewrite->using_permalinks() ){
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 'fp_type' , remove_query_arg( 'type' , remove_query_arg( 's', get_pagenum_link( 1 ) ) ) ) ) . 'page/%#%/', 'paged' );
}
if( !empty($wp_query->query_vars['s'] ) ){
$pagination['add_args'] = array( 's' => urlencode( get_query_var( 's' ) ) );
}
if( !empty( $wp_query->query_vars['type'] ) ){
$pagination['add_args'] = array( 'type' => get_query_var( 'type' ) );
}
if( !empty( $wp_query->query_vars['fp_type'] ) ){
$pagination['add_args'] = array( 'fp_type' => get_query_var( 'fp_type' ) );
}
$pgn = paginate_links( $pagination );
if( $current == 1 ){
$current--;
}
if(!empty($pgn)){
echo '<div class="pag">';
echo '<ul class="b_pag center p_b">';
foreach($pgn as $k => $link){
print '<li>' . str_replace( "'" , '"' , $link ) . '</li>';
}
echo '</ul>';
echo '</div>';
}
} ?>
Add this code to that page where you want to show the post.
<?php
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'cat' => '7',
'post_type' => 'post',
'posts_per_page' => 10,
'paged' => $page,
);
query_posts($args);?>
add below code after the post code:
<?php while ( have_posts() ) : the_post(); ?>
<div>
<ul>
<li>
<?php the_content(); ?>
</li>
</ul>
</div>
<?php endwhile; // end of the loop. ?>
<div class="navigation"><p><?php posts_nav_link(); ?></p></div>

Categories