Я создал некоторую AJAX разбивку на страницы для пользовательского Wordpress l oop, но я на 100% уверен, что это может быть НАМНОГО аккуратнее. Он работает в том смысле, что он перебирает сообщения, он фильтрует эти сообщения (не AJAX) при выборе раскрывающегося списка и добавляет следующую страницу сообщений при нажатии кнопки пагинации (AJAX) ... но это просто кажется, что кода много, и я хочу привести его в порядок.
L oop:
<?php
wp_reset_postdata();
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$posts_per_page = 5;
// default args if no filter is set
$args = array(
'post_type' => 'articles',
'post_status' => 'publish',
'posts_per_page' => $posts_per_page,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'cat' => 10
);
// args changed if filter is set in url
if ( isset($_GET['article_filter']) && isset($_GET['filter_value']) ) { ?>
<script>
$('html, body').animate({
scrollTop: $('#index-posts-wrapper').offset().top - 120
}, 600);
</script>
<?php
$filter = $_GET['article_filter'];
$filter_value = $_GET['filter_value'];
if ( $filter == 'year' ) {
$args = array(
'post_type' => 'articles',
'post_status' => 'publish',
'date_query' => array(
'year' => intval($filter_value)
),
'posts_per_page' => $posts_per_page,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'cat' => 10
);
} else if ( $filter == 'month' ) {
$month_and_year = explode('-', $filter_value);
$month = intval($month_and_year[0]);
$year = intval($month_and_year[1]);
$args = array(
'post_type' => 'articles',
'post_status' => 'publish',
'date_query' => array(
'year' => $year,
'month' => $month
),
'posts_per_page' => $posts_per_page,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'cat' => 10
);
} else if ( $filter == 'author' ) {
$args = array(
'post_type' => 'articles',
'post_status' => 'publish',
'author' => intval($filter_value),
'posts_per_page' => $posts_per_page,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'cat' => 10
);
}
} // end if ( isset($_GET['article_filter']) && isset($_GET['filter_value']) )
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $date = get_the_date(); ?>
<div class="post postnumber<?php echo $count ?>">
<div class="tag-dark">
<?php echo $date ?>
</div>
<div class="h4-dark">
<?php print the_title()?>
</div>
<div class="p-dark">
<?php the_excerpt()?>
</div>
<div class="buttoncontainer">
<a href="<?php echo get_the_permalink(); ?>" class="btn-large-accent-center">READ
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 512"><path d="M166.9 264.5l-117.8 116c-4.7 4.7-12.3 4.7-17 0l-7.1-7.1c-4.7-4.7-4.7-12.3 0-17L127.3 256 25.1 155.6c-4.7-4.7-4.7-12.3 0-17l7.1-7.1c4.7-4.7 12.3-4.7 17 0l117.8 116c4.6 4.7 4.6 12.3-.1 17z"/></svg>
</a>
</div>
</div>
<?php $count++ ?>
<?php endwhile;
echo '<div class="pagination">';
echo paginate_links( array(
'base' => get_pagenum_link(1) .'%_%',
'format' => 'page/%#%/',
'current' => max( 1, get_query_var('paged') ),
'total' => $loop->max_num_pages,
'prev_text' => __('«'),
'next_text' => __('»'),
'show_all' => false,
'mid_size' => 2,
'end_size' => 1,
) );
echo '</div>';
wp_reset_postdata(); ?>
Функции. php
function my_scripts()
{
wp_enqueue_script( 'ajax-pagination', get_stylesheet_directory_uri() . '/js/ajax-pagination.js', array( 'jquery' ), '1.0', true );
global $loop;
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'my_scripts');
add_action( 'wp_ajax_nopriv_ajax_pagination', 'my_ajax_pagination' );
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_pagination' );
function my_ajax_pagination() {
$paged = $_POST['page'];
$posts_per_page = 5;
// default args if no filter is set
$args = array(
'post_type' => 'articles',
'post_status' => 'publish',
'posts_per_page' => $posts_per_page,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'cat' => 10
);
// args changed if filter is set in url
if ( isset($_GET['article_filter']) && isset($_GET['filter_value']) ) {
?>
<script>
$('html, body').animate({
scrollTop: $('#index-posts-wrapper').offset().top - 120
}, 600);
</script>
<?php
$filter = $_GET['article_filter'];
$filter_value = $_GET['filter_value'];
if ( $filter == 'year' ) {
$args = array(
'post_type' => 'articles',
'post_status' => 'publish',
'date_query' => array(
'year' => intval($filter_value)
),
'posts_per_page' => $posts_per_page,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'cat' => 10
);
} else if ( $filter == 'month' ) {
$month_and_year = explode('-', $filter_value);
$month = intval($month_and_year[0]);
$year = intval($month_and_year[1]);
$args = array(
'post_type' => 'articles',
'post_status' => 'publish',
'date_query' => array(
'year' => $year,
'month' => $month
),
'posts_per_page' => $posts_per_page,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'cat' => 10
);
} else if ( $filter == 'author' ) {
$args = array(
'post_type' => 'articles',
'post_status' => 'publish',
'author' => intval($filter_value),
'posts_per_page' => $posts_per_page,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $paged,
'cat' => 10
);
}
} // end if ( isset($_GET['article_filter']) && isset($_GET['filter_value']) )
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php $date = get_the_date(); ?>
<div class="post postnumber<?php echo $count ?>">
<div class="tag-dark"><?php echo $date ?></div>
<div class="h4-dark"><?php print the_title()?></div>
<div class="p-dark"><?php the_excerpt()?></div>
<div class="buttoncontainer"><a href="<?php echo get_the_permalink(); // echo Get_most_recent_permalink() ?>" class="btn-large-accent-center">READ<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 512"><path d="M166.9 264.5l-117.8 116c-4.7 4.7-12.3 4.7-17 0l-7.1-7.1c-4.7-4.7-4.7-12.3 0-17L127.3 256 25.1 155.6c-4.7-4.7-4.7-12.3 0-17l7.1-7.1c4.7-4.7 12.3-4.7 17 0l117.8 116c4.6 4.7 4.6 12.3-.1 17z"/></svg></a></div>
</div>
<?php $count++ ?>
<?php
endwhile;
die();
}
JS:
(function($) {
function find_page_number( element ) {
element.find('span').remove();
return parseInt( element.html() );
}
$(document).on( 'click', '.pagination a', function( event ) {
event.preventDefault();
page = find_page_number( $(this).clone() );
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
page: page
},
success: function( html ) {
$('#index-posts-wrapper').append( html );
}
})
})
})(jQuery);
I ' Я надеюсь, что кто-то сможет улучшить его, чтобы он стал супер гладким. Я думаю, что могу привести в порядок аргументы фильтра (поэтому, если выбран раскрывающийся фильтр, мне не нужно снова определять каждый аргумент), и я также думаю, что могу закодировать аргументы в json, поэтому я не запустить все $ args снова в вызове AJAX ... Но я просто не могу понять, как это сделать. :(
Есть идеи?