Exploring the possibilities of custom query pagination and Ajax in Wordpress

My Wordpress website has custom category and single pages with a unique query. The pagination is set up to load posts on the same page, which works fine on the homepage.

The issue arises when trying to use pagination in single pages and categories using

<?php previous_posts_link('&laquo; Previous') ?>
. This script does not work as intended for these specific pages.

Below is the code snippet:

<div class="main_container">
<div id="load_posts_container">
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
   $args=array(
      'post_type'=>'post',
      'cat' => '-28' . $category_ID,
      'posts_per_page' => 8,
      'paged'=>$paged
   );
   $temp = $wp_query;
   $wp_query= null;
   $wp_query = new WP_Query($args);

   if ( $wp_query->have_posts() ) : while ( $wp_query->have_posts() ) : $wp_query->the_post();   ?>
<!--ARTICLES MARKUP HERE-->
<?php   endwhile; endif; 
   ?>
<!--//load_posts_container-->
<
<div class="load_more_cont">
   <p>More events <br/>
      <span class="load_more_text"><?php next_posts_link('<img src="' . get_bloginfo('stylesheet_directory') . '/images/load-more-image.png" alt="More Events in Rome"/>', $wp_query->max_num_pages) ?></span>
   </p>
</div>
<!--//load_more_cont-->
<?php $wp_query = null;
   $wp_query = $temp;
   wp_reset_query(); ?>
<script type="text/javascript">
   // Ajax-fetching "Load more posts"
   $('.load_more_cont a').live('click', function(e) {
    e.preventDefault();
    $.ajax({
        type: "GET",
        url: $(this).attr('href') + '#main_container',
        dataType: "html",
        success: function(out) {
            result = $(out).find('#load_posts_container .home_post_box');
            nextlink = $(out).find('.load_more_cont a').attr('href');

            $('#load_posts_container').append(result);

            if (nextlink != undefined) {
                $('.load_more_cont a').attr('href', nextlink);
            } else {
                $('.load_more_cont').remove();
                $('#load_posts_container').append('<div class="clear"></div>');
            }

            if (nextlink != undefined) {
                $.get(nextlink, function(data) {
                             if($(data + ":contains('home_post_box')") != '') {
                                 $('#load_posts_container').append('<div class="clear"></div>');        
                             }
                           });                        
                       }

        }
    });
   });
</script>

Any suggestions or ideas for improvement?

Answer №1

If WordPress is having trouble interpreting the paged query variable for those specific pages (which I have yet to confirm), you could consider bypassing get_query_var('paged') and opting for good old-fashioned $_GET['paged']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with MUI Data Grid sorting: Data Grid sortComparator function returning undefined

I'm attempting to organize data with nested values in a data grid, but I keep receiving 'undefined' on the sortComparator of Data Grid Columns. Code: Column Data Setup: { headerName: 'Title', field: `${this.props.type} ...

Guide on submitting a form through the Angular 2 HTTP post method with JavaScript

Currently working on grasping the concepts of Angular2, but facing challenges when attempting to utilize http.post() for submitting a form to my Web API. ...

designing the border at the bottom of the existing menu selection

I am trying to enhance the look of my current-menu-item div by adding a border at the bottom. It seems simple enough to achieve this by simply including the border in the div. However, I'm facing an issue with the width and position of the border. Ide ...

The process of examining a function that includes the invocation of an additional API function in a NodeJS environment

I'm faced with a situation where I have a nested function inside another function. The second function is responsible for making an API call. However, in order to write a unit test for this scenario, I need to avoid actually making the real API call a ...

Guidelines on transforming a Java Object list into JSON format and displaying it through AJAX requests

Currently, I am facing an issue where I have a Java object list retrieved from the database as an ArrayList of objects. I need to display this on a JSP page using AJAX. While I know how to display an ArrayList of Strings via AJAX in a JSP page, I'm st ...

Unique alphanumeric code following the inclusion of a JavaScript file

I'm encountering an issue with a webpage that incorporates two JavaScript files. When inspecting it using firebug, I noticed that every time the page loads, these two files are included with the prefix ?_=someRandomNumber I'm unsure about the or ...

Assistance needed: For each loop not iterating properly following variable explosion

I'm struggling to display a row from a database that contains a list of skills as an array delimited by commas. I have provided fully annotated code with an explanation below of what I have done so far. Any help would be greatly appreciated. Thank you ...

Exploring the process of defining and authenticating an array of objects utilizing cuid as the key and ensuring the object contains designated properties

I have a customized data set that requires validation: { "name": "Some unique name", "blocks": [ {"cj5458hyl0001zss42td3waww": { "quantity": 9, "rate": 356.77, ...

Seamless infinite background scrolling on the canvas without any disruptions

In my HTML5/JS project, I have implemented infinite background scrolling using multiple canvases. The challenge I am facing is that while the animation is smooth after rendering, there is a quick hiccup when transitioning to the next frame due to the need ...

CSS: elements that are only visible when positioned above specific elements

Can we create an element that is only visible above specific other elements? For instance, in the following code snippet, I want the .reflection element to be visible only above the .reflective elements (located at the top and bottom) and not visible on t ...

JS: Initiating a new keypress operation

When I press the Tab key, I want it to do something different instead of its default action. Specifically, I have a text box selected and I would like it to add spaces (essentially making the textarea behave like a text editor). How can I trigger this type ...

iterating over a large multidimensional array in JavaScript

I am facing a challenge with handling a large JSON dataset (around 20k+ entries, totaling over 2mb) that I need to display on my web pages. Currently, I fetch this data using AJAX and parse it using JSON.parse in JavaScript, resulting in a complex multidi ...

Having Trouble Parsing JSON Object with JQuery?

I'm having trouble extracting data from a valid JSON object using jQuery/JavaScript - it always returns as 'undefined'. var json = (the string below). var obj = $.parseJSON(JSON.stringify(JSON.stringify(json))); alert(obj); // aler ...

Unable to invoke the setState function within the onSubmit handler of Formik

Every time I submit my form, I want to display an alert. I attempted to pass my state as a prop to the component, but it didn't work. Here's how my class state looks: this.state = { alert_variant: '', alert_heading: ...

The div is incorrect and causing the label and input to move in the wrong direction

Whenever I try to adjust the position of the current-grade-name-input, the entire grade-point-input moves along with it inexplicably. /* final grade calculator: (wanted-grade - (current-grade * (1 - final%))) / final% Ex: have a 80 an ...

Angular JS - Establishing a Connection to Woocommerce OAuth v1

I'm having trouble authenticating myself with the rest service. I attempted to use this library to generate all the necessary parameters as mentioned here, and I constructed the request like this: $scope.oauth = new OAuth({ consumer: { p ...

unable to show image retrieved from JSON data

Looking to showcase the data from my JSON objects, which are displayed in 2 images below https://i.stack.imgur.com/yhqFy.png https://i.stack.imgur.com/DUgFO.png In the data, I have properties like c_name, max_slots, and an array slots. Within the array, ...

Is the ID selector the quickest method in jQuery and CSS?

Which is the optimal choice in jQuery/javascript for speed? $('#myID .myClass') or $('.myClass') What is the preferred option to utilize in CSS? #myID .myClass{} or .myClass{} In hindsight, I realize my explanation was insuffici ...

What is the best way to display the letter X (Clear) in the Chrome INPUT field with the type

A custom application was developed that utilizes an input field of the number type: <input type="number" min="-1000000" max="1000000" step="0.01"> Within Internet Explorer, there is a small "clear" or [X] button on the right side of the input field ...

Iterate over an array in JavaScript and include the elements as parameters in an SQL query

Can I set an SQL string to a variable in JavaScript and populate part of it by looping through an array? Here is the initial SQL: var tag = ["fun", "beach", "sun"]; var sql = "SELECT * FROM myTable " +"WHERE id > 5" //... // L ...