Adding Pagination to a wordpress post list - javascript

I am trying to add pagination to this post list https://cutt.ly/tjuH6lJ , the code i used was
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
<!-- the shortcode to the list -->
...............................
<script>
var myList = new List('main_blog', {
valueNames: ['pis-li'],
page: 3,
pagination: true
});
</script>
I also tried the PHP pagination code and added it to my functions.php
function pagination_nav() {
global $wp_query;
if ( $wp_query->max_num_pages > 1 ) { ?>
<nav class="pagination" role="navigation">
<div class="nav-previous"><?php next_posts_link( '← Older posts' ); ?></div>
<div class="nav-next"><?php previous_posts_link( 'Newer posts →' ); ?></div>
</nav>
<?php }}
and invoke it with <?php pagination_nav(); ?>
i am using the "Extra" theme from "DIVI" and the post list was made with a plugin called "Posts in Sidebar"

You are looking for the_posts_pagination() function.
Displays a paginated navigation to next/previous set of posts, when applicable.
Source # https://developer.wordpress.org/reference/functions/the_posts_pagination/
It uses the arguments of the get_the_posts_pagination and paginate_links() functions.
See get_the_posts_pagination() for available arguments.
Source # https://developer.wordpress.org/reference/functions/get_the_posts_pagination/
Source # https://developer.wordpress.org/reference/functions/paginate_links/
Pagination & loop
<?php
if( have_posts() ):
while( have_posts() ): the_post();
echo '<article>';
if( get_the_title() !== '' ):
esc_attr( the_title( '<h1>', '</h1>' ) );
endif;
if( get_the_content() !== '' ):
esc_attr( the_content() );
endif;
echo '<article>';
endwhile;
/**
* the_posts_pagination
* Displays a paginated navigation to next/previous set of posts, when applicable.
* #link https://developer.wordpress.org/reference/functions/the_posts_pagination/
* #link https://developer.wordpress.org/reference/functions/get_the_posts_pagination/
* #link https://developer.wordpress.org/reference/functions/paginate_links/
*/
the_posts_pagination( array(
'screen_reader_text' => ' ',
'prev_text' => '←',
'next_text' => '→',
'show_all' => true,
) );
else:
echo 'No posts yet!';
endif; ?>
If I remember correctly by default, Wordpress will show 12 posts, before showing the pagination.

Related

Display category post list based on the current posts category

Does anyone know how I can display a list of WordPress posts based on the current post pages current category?
For example if I'm currently on post333.html & the category the page falls under is "Drinks".
How would I get the rest of the posts under that category to display in a list as 'suggested topics' on post333.html.
And if the post & category changes so will the list.
The following code should go directly into your template file.
<?php
// Get Other posts in same category
$suggested_posts = get_posts( array(
'category__in' => wp_get_post_categories( $post->ID ), // Retrieve the list of categories for a post.
'numberposts' => 5, // Number of posts
'post__not_in' => array( $post->ID ) // Exclude current post
) );
// If post found
if( $suggested_posts ) {
foreach( $suggested_posts as $post ) {
setup_postdata($post); ?>
<ul>
<li>
<?php the_title(); ?>
<?php the_content('Read the rest of this entry »'); ?>
</li>
</ul>
<?php }
}
wp_reset_postdata();
?>
If you want to use it anywhere then you may create a shortcode like below.
<?php
function yourprefix_suggested_posts( $atts ){
// Get Other posts in same category
$suggested_posts = get_posts( array(
'category__in' => wp_get_post_categories( $post->ID ), // Retrieve the list of categories for a post.
'numberposts' => 5, // Number of posts
'post__not_in' => array( $post->ID ) // Exclude current post
) );
// If post found
if( $suggested_posts ) {
foreach( $suggested_posts as $post ) {
setup_postdata($post); ?>
<ul>
<li>
<?php the_title(); ?>
<?php the_content('Read the rest of this entry »'); ?>
</li>
</ul>
<?php }
}
wp_reset_postdata();
}
add_shortcode( 'suggested_posts', 'yourprefix_suggested_posts' );
?>
Later you can use [suggested_posts] shortcode anywhere.
(Not tested but it should work.)

Getting AJAX load more to work with custom Wordpress related posts Query?

I"m using the tutorial from this blog post to implement Ajax Load More functionality. https://rudrastyh.com/wordpress/load-more-posts-ajax.html
I've successfully implemented this on my archive page for all blog posts. However, I've got several "RElated Posts" sections that use custom WP Queries that I can't get to work. I've tried the solution in this comment: https://rudrastyh.com/wordpress/load-more-posts-ajax.html#comment-1055
It loads new posts, but they are not adhering to the argumenets of the custom query (specifically displaying posts only in the same category).
The custom query is working (it displays 4 related posts from the same category). When i'm loading more, it is not respecting pagination (it's loading 6 posts instead of 4) and it is not respecting the query (it is loading posts not in the same category).
<div class="related-blog-posts gray-bg pt-5 pb-5 blog">
<div class="related-title pb-3">
<h1 class="mb-2">Related Stories</h1>
<img src="/dcustom/wp-content/uploads/2019/04/Path-137#2x.png" />
</div><!-- scroll-down-->
<div class="container">
<div class="row">
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query_args = array(
'category__in' => wp_get_post_categories( $post->ID ),
'paged' => $paged,
'post_type' => 'post',
'posts_per_page' => 4,
'post__not_in' => array( $post->ID ),
'orderby' => 'date',
'order' => 'DESC'
);
$third_query = new WP_Query( $query_args ); ?>
<?php
//Loop through posts and display...
if($third_query->have_posts()) : ?>
<?php while ($third_query->have_posts() ) : $third_query->the_post(); ?>
<?php get_template_part('template-parts/content-related-blog-posts'); ?>
<?php endwhile; ?><!-- end the loop-->
<?php endif; ?>
<?php wp_reset_postdata(); ?>
<?php // don't display the button if there are not enough posts
if ( $third_query->max_num_pages > 1 )
echo '<a class="custom_loadmore btn btn-primary">More posts</a>'; // you can use <a> as well
?>
<?php endif; ?><!-- end loop if--->
</div><!-- row -->
</div><!-- container -->
</div><!-- related-case-studies-->
<script>
var test = '<?php echo serialize( $third_query->query_vars ) ?>',
current_page_myajax = 1,
max_page_myajax = <?php echo $third_query->max_num_pages ?>
</script>
<script src="<?php bloginfo('template_url')?>/js/myloadmore.js"></script>
jQuery(function($){ // use jQuery code inside this to avoid "$ is not defined" error
$('.misha_loadmore').click(function(){
var button = $(this),
data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
'page' : misha_loadmore_params.current_page
};
$.ajax({ // you can also use $.post here
url : misha_loadmore_params.ajaxurl, // AJAX handler
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().after(data); // insert new posts
misha_loadmore_params.current_page++;
if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page )
button.remove(); // if last page, remove the button
// you can also fire the "post-load" event here if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.remove(); // if no data, remove the button as well
}
}
});
});
$('.custom_loadmore').click(function(){
//custom query on front-page.php
var button = $(this),
data = {
'action': 'loadmore',
'query': test,
'page' : current_page_myajax
};
$.ajax({
url : '/dcustom/wp-admin/admin-ajax.php', // AJAX handler
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().after(data); // insert new posts
current_page_myajax++;
if ( current_page_myajax == max_page_myajax )
button.remove(); // if last page, remove the button
} else {
//button.remove(); // if no data, remove the button as well
}
}
});
});
});
function misha_my_load_more_scripts() {
global $wp_query;
// In most cases it is already included on the page and this line can be removed
wp_enqueue_script('jquery');
// register our main script but do not enqueue it yet
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') );
// now the most interesting part
// we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
// you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages,
) );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
/* AJAX LOOP FOR THE ARCHIVE PAGE */
function misha_loadmore_ajax_handler(){
// prepare our arguments for the query
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
// it is always better to use WP_Query but not here
query_posts( $args );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post();
// look into your theme code how the posts are inserted, but you can use your own HTML of course
// do you remember? - my example is adapted for Twenty Seventeen theme
get_template_part( 'template-parts/content-index', get_post_format() );
// for the test purposes comment the line above and uncomment the below one
// the_title();
endwhile;
endif;
die; // here we exit the script and even no wp_reset_query() required!
}
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}

Updating / refreshing custom mini-cart with ajax in Woocommerce

I am trying to build a simple interface in Woocommerce where a product gets added straight to the mini cart next to it with AJAX, rather than having the page refresh every time you add an item to the cart. Unfortunately I cannot get the AJAX to work and the page just keeps refreshing.
woocommerce.php - the default woocommerce page:
<?php
//LOOP THROUGH ALL PRODUCTS
$args = array( 'post_type' => 'product');
$loop = new WP_Query( $args );
echo "<ul class='mylisting'>";
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$id = $product->get_id();
$item_name = $product->get_name();
if( $product->is_type( 'variable' ) ){
$class = "variable-product";
} else {
$class = NULL;
}
//OUTPUT PRODUCTS
?>
<li>
<a class="menu-link <?php echo $class; ?>" data-product_id="<?php echo $id; ?>" href="/wpdev/shop/?add-to-cart=<?php echo $id; ?>"><?php echo $item_name." - ".$id; ?></a>
</li>
<?php if( $product->is_type( 'variable' ) ) : ?>
<div id="product-popup-<?php echo $id; ?>" class="product-popup">
<div class="popup-inner">
<?php woocommerce_variable_add_to_cart(); ?>
</div>
</div>
<?php endif; ?>
<?php
endwhile;
echo "</ul>";
wp_reset_query();
?>
<!-- DISPLAY MINI CART -->
<div id="mini-cart-container">
<?php woocommerce_mini_cart(); ?>
</div>
main.js - Main javascript file:
$('.menu-link').click(function(){
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});
functions.php
function ajax_update_mini_cart() {
echo wc_get_template( 'cart/mini-cart.php' );
die();
}
add_filter( 'wp_ajax_nopriv_ajax_update_mini_cart', 'ajax_update_mini_cart' );
add_filter( 'wp_ajax_ajax_update_mini_cart', 'ajax_update_mini_cart' );
The goal is to get the woocommerce_mini_cart() function to update with ajax. Is this possible?
I suspect the problem lies with the way I have coded the javascript ajax function, but I'm not sure. Any help would be greatly appreciated.
UPDATE: Moe's solution below has now been added, which has stopped the page reloading but the cart still doesn't update. Echoing some text inside the ajax_update_mini_cart() function does ajax that text inside the mini-cart-container div where the mini-cart should be, which proves (I think) that the javascript function and the php function is working. I think for some reason the problem comes when the echo wc_get_template( 'cart/mini-cart.php' ); is placed inside the function. Does anyone know why this is?
its following the href. try the following
$('.menu-link').click(function(e){
e.preventDefault();
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});

Can you remove wordpress post tags with js/php after certain date (ACF date time picker)?

So my website lists upcoming film screenings in my area.
I'm using the ACF date time picker to only show posts/film screenings that are in the future in the wordpress loop.
I have tags filtering the results dynamically using ajax (thanks to https://www.bobz.co/ajax-filter-posts-tag/) except there are tags that aren't relevant to the results because they belong to posts that are older than the current date (past screenings).
*For example on the website, the 'animated film festival' is still coming up with the other tags.
I don't know if it's possible to delete a posts tags with PHP (within the post template while it loops through other posts) - and to delete the posts tags if the ACF date time field for that post is older than the current date.
I haven't found much luck googling this and I am a bit of a noob so...
This is my site: http://pigcine.pamrosel.com/
This is what I'm doing in my functions.php file at the moment:
// Get all tags and display
function tags_filter() {
$tax = 'post_tag';
$terms = get_terms( $tax );
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<?php
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '' . $term->name . ' ';
} ?>
</div>
<?php endif; }
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce($_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
// WP Query
$args = array(
'tag' => $taxonomy,
'post_type' => 'post',
'posts_per_page' => -1,
'meta_key' => 'datetime',
'orderby' => array(
'datetime' => 'ASC'
),
);
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while($query->have_posts()) : $query>the_post();
$today = date('Y-m-d H:i:s', strtotime('+9 hours'));
$event_date = get_field('datetime');
if (strtotime($today) <= strtotime($event_date)) {
?>
<div class="sl">
<div class="sl_closed">
<div class="col-2-8"><div class="modulepad">
<p><?php the_field('datetime'); ?></p>
</div></div>
<div class="col-3-8"><div class="modulepad">
<p><?php the_title(); ?><br>
<?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["directors"]); ?>
</p>
</div></div>
<div class="col-3-8"><div class="modulepad">
<p><?php the_field('location_name'); ?><br>
<?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["countries"]) . " "; echo $movie["released"] . " "; echo implode(", ", $movie["runtime"]); ?>
</p>
</div></div>
</div><!--SL_CLOSED-->
<?php } endwhile; ?>
<?php else: ?>
<h2>No posts found</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');

Wordpress Custom Post Type Popup—jquery and ajax?

I'm trying to use jquery (bpopup)to load a custom post type post into a popup window. An example of what I'm trying to do is at http://outpost.la —just click on any of the images to see the popup.
I think I ultimately need to write a function to do this, but I'm not sure about how to do that. So far I just have two snippets of code—"button that triggers popup" and "element to pop up"—in my page template. The first snippet is doing what I want: displaying the series of custom post type titles as buttons. But the second snippet which is supposed to display the custom post type content in the popup is showing the titles + content of all of the custom post types.
Screenshot of the Popup w/ buttons in the background:
http://cl.ly/image/1f0G0c2s2J3U
Code:
`
<!-- Button that triggers the popup -->
<?php
$args = array(
'post_type' => 'portfolio_project',
'posts_per_page' => -1 );
$loop = new WP_Query( $args );
$i = 0;
echo'<button class="my-button">';
while ( $loop->have_posts() ) : $loop->the_post();
if ($i % 0 == 0 && $i > 0) {
echo '</button>' . "\n" . '<button class="my-button">';
};
?>
<?php the_title(); ?>
<?php
$i++;
endwhile;
echo '</button>';
?>
<!-- Element to pop up -->
<div id="element_to_pop_up">
<?php
// the query
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
<!-- end custom post type loop -->
</div>
<!-- END Element to pop up -->
<script>
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('.my-button').bind('click', function(e) {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('#element_to_pop_up').bPopup({
appendTo: 'body'
, position: ['auto','0']
, positionStyle: 'fixed'
, scrollBar: 'false'
});
});
});
})(jQuery);
</script>
`
Actually Wordpress uses a different approach for ajax request. You have to understand that first. So, the simple prototype is something like this
// In your functions.php file
add_action( 'wp_ajax_nopriv_ MyAjaxAction', 'MyAjaxFunction' );
add_action( 'wp_ajax_ MyAjaxAction', 'MyAjaxFunction' );
function MyAjaxFunction() {
// do query for your posts
// process it
// echo it
die();
}
In your client side/jQuery code
$(function(){
$('.myButton').on('click', function(e){
e.preventDefault();
// other code
$.ajax({
'url':'/wp-admin/admin-ajax.php', // admin-ajax.php will handle the request
'type':'post',
'data': {
// this is the action hook to call the handler "MyAjaxFunction"
'action': 'MyAjaxAction',
// pass some data to post variblr to use in php/wordpress (optional)
'id':'someId' // you can retrieve this using $_POST['id'];
},
'success':function(data){
// returned data by wordpress
}
});
});
});
This is the proper way to handle ajax request in WordPress, read this article for more help and as a bonus download this book.

Categories