i have custom php template for display all posts (from ACF). I need display only first 6 and after click on button load another 6.
My code:
JS
<script>
$(document).ready(function(){
$(".content").slice(0, 6).show();
$("#loadMore").on("click", function(e){
e.preventDefault();
$(".content:hidden").slice(0, 6).slideDown();
if($(".content:hidden").length == 0) {
$("#loadMore").text("No Content").addClass("noContent");
}
});
})
</script>
PHP
$args = array(
'posts_per_page' => -1,
'post_type' => 'dluhopisy',
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ){
while ( $the_query->have_posts() ){
$the_query->the_post();
$the_id = get_the_id();
HTML
Load More
Related
I Need to Redirect a Custom Page If the Product Count is Zero in a Woocommerce Category Kindly Help me
Assuming that you are accessing the product categories via one of the taxonomy term pages:
Add this to your functions.php file. Make sure you replace SOME_PATH . '/some-custom-file.php'; with the path to the template you would like to load.
add_filter( 'template_include', 'redirect_on_empty_product_category' );
function redirect_on_empty_product_category( $template ){
if ( ( $taxonomy_id = get_query_var( 'taxonomy' ) ) && ( $term_id = get_query_var( 'term' ) ) && is_tax( $taxonomy_id, $term_id ) ){
$term = get_term_by( 'slug', $term_id, $taxonomy_id );
if ( $term->count === 0 ){
$page_url = get_permalink($some_post_id);
echo sprintf('<script type="text/javascript"> window.location = "%s" </script>', $page_url);
}
}
return $template;
}
You just need to add $cat->count to get the count of all products in that category. Hope this helps you out.
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms( 'product_cat', $args );
foreach( $product_categories as $cat ) {
echo $cat->name.' ('.$cat->count.')';
}
Thanks
I am trying to load my sidebars in my while loop by using if statements that call them after a certain number of posts. It's important to note that I am using AJAX code (provided below) to load in posts on scroll and I believe it may be causing the issue.
Though they are sidebars, they are not physically a sidebar but rather content loaded between posts.
I've tried for a week to locate the problem but I cannot seem to get the sidebars to load with AJAX as a if statement in the while loop.
Important to note: The sidebar will load after the number of posts if it's not loaded through AJAX. So if it's in the initial load, the sidebars load. But when you continue to scroll to say the third or fourth bar it will not load and the AJAX will only load the (parts/content).
I need to either be able to resolve the if statement so it works within the while loop that loads through AJAX or I'm open to an alternate solution as long as it doesn't remove the AJAX.
A lot of work has been put into making this loop work and help is greatly appreciated!
front-page.php
<?php
$current_page = max( 1, get_query_var( 'paged' ) );
$the_query = new WP_Query( array(
'cat' => '-21',
'post_type' => 'post',
'posts_per_page' => 5,
'paged' => $current_page,
'tax_query' => array(
array(
'taxonomy' => 'topics',
'operator' => 'NOT EXISTS',
'field' => 'term_id',
'terms' => $term_id
)
)
) );
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ),
'posts' => json_encode( $the_query->query_vars ),
'current_page' => $current_page,
'max_page' => $the_query->max_num_pages
) );
?>
<div id="main" class="container-fluid">
<?php if ($the_query->have_posts()) : ?>
<?php $count = 0; ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); get_template_part( 'parts/content', get_post_format() ); ?> <!-- This parts/content loads -->
<?php $count++; ?>
<!-- the dynamic_sidebar does not load -->
<?php if ($count == 2 && is_active_sidebar('sidebar1') ) : ?>
<div class="side-container first-side">
<?php dynamic_sidebar('sidebar1'); ?>
</div>
<?php endif; ?>
<?php if ($count == 10 && is_active_sidebar('sidebar2') ) : ?>
<div class="side-container first-side">
<?php dynamic_sidebar('sidebar2'); ?>
</div>
<?php endif; ?>
<?php if ($count == 20 && is_active_sidebar('sidebar3') ) : ?>
<div class="side-container third-side">
<?php dynamic_sidebar('sidebar3'); ?>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<?php get_footer(); ?>
</div><!-- END CONTAINER -->
parts/content -- this loads as expected including code if it's helpful
<div class="row post"> <!-- Post is mentioned in the below JS to load -->
<div class="col-sm-5">
<h2>Text</h2>
</div>
<div class="col-sm-7">
<h3>text</h3>
</div>
</div><!-- END ROW-->
sidebar code - works when initially loaded but doesn't when AJAX calls on this code such as the last two sidebars in front-page.php
<?php
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?>
<?php while( $flexible_posts->have_posts() ) : $flexible_posts->the_post(); global $post; ?>
<div class="sidebar-area">
//sidebar code here
}
endwhile;
?>
myloadmore.js - AJAX Call
jQuery(function($){
var canBeLoaded = true,
bottomOffset = 2000;
$(window).scroll(function(){
if ( misha_loadmore_params.current_page >= misha_loadmore_params.max_page ) {
return;
}
var data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data: data,
type: 'POST',
beforeSend: function( xhr ){
// AJAX call is in process, we shouldn't run it again until complete
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#main').find('div.post:last-of-type').after( data ); // where to insert posts
canBeLoaded = true; // the ajax is completed, now we can run it again
misha_loadmore_params.current_page++;
bottomOffset = ( $( '#main > div.post:last' ).offset() || {} ).top
}
}
});
}
});
});
functions.php - Added for further context
function misha_my_load_more_scripts() {
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js',
array( 'jquery' ), '', true );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
function misha_loadmore_ajax_handler() {
$args = json_decode( wp_unslash( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // load the next page
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'parts/content', get_post_format() );
endwhile;
endif;
wp_die();
}
add_action( 'wp_ajax_loadmore', 'misha_loadmore_ajax_handler' ); // Authenticated users
add_action( 'wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users
The trick here was to add the if statements inside of the AJAX handlers as well. Perhaps someone with AJAX experience can add to this one day to explain why it works, but all I know is that it does. All the code from my question is the same below is the difference from the functions.php ajax handler function.
function misha_loadmore_ajax_handler() {
$args = json_decode( wp_unslash( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // load the next page
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
get_template_part( 'parts/content', get_post_format() );
<?php if ($count == 2 && is_active_sidebar('sidebar1') ) : ?>
<div class="side-container first-side">
<?php dynamic_sidebar('sidebar1'); ?>
</div>
<?php endif; ?>
<?php if ($count == 10 && is_active_sidebar('sidebar2') ) : ?>
<div class="side-container first-side">
<?php dynamic_sidebar('sidebar2'); ?>
</div>
<?php endif; ?>
<?php if ($count == 20 && is_active_sidebar('sidebar3') ) : ?>
<div class="side-container third-side">
<?php dynamic_sidebar('sidebar3'); ?>
</div>
<?php endif;
endwhile;
endif;
wp_die();
}
I have a PHP code that creates a JSON data from wordpress posts in the database.
I load this JSON on my html page using AJAX.
The above works fine.
Now I need to add a "Load More" button so everytime its pressed, we load another 10 posts and append/add them to the ones that were already loaded WITHOUT having to delete the old ones and re-adding them.
So this my AJAX code for loading more:
var i = 0;
$(document).on("click", ".loadMoreBtn", function () {
$.ajax({
url: 'https://some-domain.com/index.php?t=' + mainCat + '&page=' + i + '',
dataType: 'json',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
if (!$.trim(data)) {
}
else {
}
$.each(data, function (pi, item) {
var id = item.id;
var img = item.img;
var title = item.title;
var date_added = item.date_added;
var item = '' + title + '';
$('.myDiv').before(item);
i++;
});
},
error: function () {
//error handling////
}
});
});
And this is my PHP code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
$t = $_GET['t'];
$page = $_GET['page'];
$posts = get_posts(array(
'posts_per_page' => $page, //add -1 if you want to show all posts
'post_type' => 'post',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $t //pass your term name here
)
))
);
$output= array();
foreach( $posts as $post ) {
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
$mysqldate = $post->post_date;
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'F d Y', $phpdate );
// Pluck the id and title attributes
$output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'date_added' => $mysqldate, 'img' =>$feat_image );
}
echo json_encode( $output );
When I click on the 'Load More' button, it acts strangely! it basiclaly adds the old data and multiplies the same ones and adds/loads some new ones as well.
I know I am missing something in my PHP code but I couldn't figure out what.
Could someone please advice on this issue?
Thanks in advance.
The error is in your wordpress query. "posts_per_page" set how many posts will be loaded. Set that as how many post should be loaded like 12 or something.
The parameter your want to set as your $page parameter is "paged".
Eg. $query = new WP_Query( array( 'paged' => 6 ) ); // page number 6
https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters
You could also use WP API instead of rolling your own
I'm loading paged posts with a loop that has two different formats. I use a counter to determine if the post is the first post. If it is then it is formatted this way, if else (not first post) then format it another way.
I'm using js to load in paged posts when user scrolls to the bottom and it all works, however, it loads the paged post with the first post in format A. I need it to load all paged posts but make them in format B. How can I do this?
My php wordpress loop to load posts:
<?php
// set up or arguments for our custom query
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'paged' => $paged
);
// create a new instance of WP_Query
$the_query = new WP_Query( $query_args );
?>
<?php if ( $the_query->have_posts() ) : $counter = 1; while ( $the_query->have_posts() ) : $the_query->the_post(); if( $counter == 1 ) { ?>
<article id ="featured">
Format A
</article>
<?php } else {?>
<article id="non-featured">
Format B
</article>
<?php }
$counter++;
endwhile;
endif;
?>
My JS:
jQuery(function(){
var page = 2;
var myurl = 'http://MyURL.com/'
var loadmore = 'on';
jQuery(document).on('scroll resize', function() {
if (jQuery(window).scrollTop() + jQuery(window).height() + 200 > jQuery(document).height()) {
if (loadmore == 'on') {
loadmore = 'off';
jQuery('#spinner').css('visibility', 'visible');
jQuery('#lazyload').append(jQuery('<div class="blog-grid" id="p' + page + '">').load(myurl + '/blog/page/' + page + ' article', function() {
page++;
loadmore = 'on';
jQuery('#spinner').css('visibility', 'hidden');
}));
}
}
});
jQuery( document ).ajaxComplete(function( event, xhr, options ) {
if ( $(".blog-grid").is(':empty'))
{
loadmore = 'off';
}
if (xhr.responseText.indexOf('class="blog-grid"') == -1) {
}
});
});
I'm really struggling to find a way to create pagination with ajax for my Wordpress posts. The solutions that I have found do not work.
To be more informative about this here is a link that has bullets at the bottom for pagination. Once these are clicked I want the effect of the site to load the new posts without triggering a page refresh.
http://maxlynn.co.uk/natural-interaction/category/all/
My question is, is there any good tutorials out there that you may have had success with for this type of effect.
Let me know if you need more information.
****** UPDATE ******
function kriesi_pagination($pages = '', $range = 2) {
$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='pagination'><div class='pagination-container'>";
if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>«</a>";
if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹</a>";
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 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>›</a>";
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>»</a>";
echo "</div>\n</div>\n";
}
}
This is my PHP that I'm using, how would I use this php to create an ajax request so that the page doesn't reload?
What you need to do is to prevent default on the pagination links, and send an AJAX request to get the posts. Wordpress works in this way for AJAX: you send all your requests to wp-admin/admin-ajax.php with an action parameter that will identify the request in order to catch it in functions.php using wp_ajax_nopriv_my_action and wp_ajax_my_action hooks.
So basically you will do this in your template file:
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.pagination a').click(function(e) {
e.preventDefault(); // don't trigger page reload
if($(this).hasClass('active')) {
return; // don't do anything if click on current page
}
$.post(
'<?php echo admin_url('admin-ajax.php'); ?>', // get admin-ajax.php url
{
action: 'ajax_pagination',
page: parseInt($(this).attr('data-page')), // get page number for "data-page" attribute
posts_per_page: <?php echo get_option('posts_per_page'); ?>
},
function(data) {
$('#content-posts').html(data); // replace posts with new one
}
});
});
});
</script>
You'll have to change classes names / attributes etc depending of your template.
And on the functions.php side:
function my_ajax_navigation() {
$requested_page = intval($_POST['page']);
$posts_per_page = intval($_POST['posts_per_page']) - 1;
$posts = get_posts(array(
'posts_per_page' => $posts_per_page,
'offset' => $page * $posts_per_page
));
foreach ($posts as $post) {
setup_postdata( $post );
// DISPLAY POST HERE
// good thing to do would be to include your post template
}
exit;
}
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_navigation' );
add_action( 'wp_ajax_nopriv_ajax_paginationr', 'my_ajax_navigation' );
The thing is to query the posts of the page requested (so we calculate the offset from the page number and the posts per page option), and display them with the template you use for single posts.
You may want to manipulate the browser history too, for that you should check on the History API.
filter.js file
$('#post-category').change(function(){
category = $(this).find('.selected').text();
postType = $('#search-form-type').val();
post_filter();
});
function post_filter(paged){
$.ajax(
{
url:ajaxUrl,
type:"POST",
data: {action:"get_post_category","category":category,'search':search, 'postType':postType, 'paged': paged},
success: function(response) {
$('#blog-post-cover').html(response);
}
});
}
$('#blog-wrapper').on('click','#pagination a',function(e){
e.preventDefault();
if ($(this).hasClass('prev')||$(this).hasClass('next')) {
paginateNum = $(this).find('.prev-next').data('attr');
post_filter(paginateNum);
}
else{
paginateNum = $(this).text();
post_filter(paginateNum);
}
$("html, body").animate({ scrollTop: 0 }, "slow");
});
postType = $('#search-form-type').val();
post_filter(1);
function.php file
add_action( 'wp_ajax_nopriv_get_post_category', 'post_category' );
add_action( 'wp_ajax_get_post_category', 'post_category' );
function post_category() {
$post_type = $_POST['postType'];
$category = $_POST['category'];
$search = $_POST['search'];
$paged = ($_POST['paged'])? $_POST['paged'] : 1;
if($post_type==="resource-center"):
$taxonomy ="resource-center-taxonomy";
else:
$taxonomy ="category";
endif;
if($category):
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $category,
),
),
'posts_per_page' => 5,
'order' => 'ASC',
's' => $search,
'paged' => $paged
);
else:
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => 5,
'order' => 'ASC',
's' => $search,
'paged' => $paged
);
endif;
$posts = new WP_Query($args);?>
<?php if ( $posts->have_posts() ) :?>
<?php while ($posts->have_posts()) : $posts->the_post(); ?>
<?php echo $post->post_title; ?>
<?php endwhile;?>
<?php
$nextpage = $paged+1;
$prevouspage = $paged-1;
$total = $posts->max_num_pages;
$pagination_args = array(
'base' => '%_%',
'format' => '?paged=%#%',
'total' => $total,
'current' => $paged,
'show_all' => false,
'end_size' => 1,
'mid_size' => 2,
'prev_next' => true,
'prev_text' => __('<span class="prev-next" data-attr="'.$prevouspage.'">«</span>'),
'next_text' => __('<span class="prev-next" data-attr="'.$nextpage.'">»</span>'),
'type' => 'plain',
'add_args' => false,
'add_fragment' => '',
'before_page_number' => '',
'after_page_number' => ''
);
$paginate_links = paginate_links($pagination_args);
if ($paginate_links) {
echo "<div id='pagination' class='pagination'>";
echo $paginate_links;
echo "</div>";
}?>
<?php wp_reset_query(); ?>
<?php else:?>
<div class="no-post-cover">
<div class="container">
<h1 class="has-no-post-list">Posts Not Found</h1>
</div>
</div>
<?php endif;?>
<?php die(1);
}