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

Checking to see if the prop 'isChecked' has been modified

I'm currently facing a challenge with testing whether a class's prop value changes after clicking the switcher. Below is the component class I am working with: import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core&a ...

Guide to encapsulating a container within a map function using a condition in JSX and TypeScript

Currently, I am working with an array of objects that are being processed by a .map() function. Within this process, I have a specific condition in mind - if the index of the object is greater than 1, it should be enclosed within a div element with a parti ...

Leveraging Cheerio in Node.js to locate a precise value within an option tag

I'm facing difficulties in selecting the exact number (in this case 7) which is the value of the option. This is what I'm attempting: var $ = cheerio.load(html); console.log($('ProductSelect').val($("option:contains('7')").v ...

Encountering issues when using react-leaflet in a React project with webpack integration

I've been attempting to import react-leaflet into my project without actually rendering any maps, but I keep getting this error message. TypeError: Object(...) is not a function I am certain that the issue stems from the import statement, as indica ...

What is the best way to showcase all tab content within a single tab menu labeled "ALL"?

I have created a tab menu example below. When you click on the button ALL, it will display all the tabcontent. Each tab content has its own tab menu. Thanks in advance! function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = doc ...

Adding a modified (id) content inline template element to another element: A step-by-step guide

In the given scenario, I am looking to achieve a function where each time the add button is clicked, the content within the template div should be appended to the element with the landingzone class. Additionally, it is important that the NEWID changes for ...

What is the most effective method to retrieve the UserName using Javascript?

Can someone please explain to me the difference between using session["user"].name and session["user:name"]? // I don't understand why we have to put the user session into the JavaScript global space :( var session = { user: { "Id":"d675c ...

Using Axios to fetch data and populating select dropdown options in a Vue component

I am currently working on integrating the response data values with my multiselect options. Although the console log displays the returned results, I'm facing difficulty in connecting them to my multiselect options. When I enter 'Day' into ...

Utilizing Javascript to filter data across multiple columns in tables

I've been experimenting with the JavaScript code below to filter table rows. The original code is from w3schools, but I made some modifications to target all input values. It works well for filtering one column, however, when I try to input a value in ...

The website that had been functioning suddenly ceased operations without any modifications

It seems like this might be related to a JavaScript issue, although I'm not completely certain. The website was working fine and then suddenly stopped. You can find the URL here - Below is the HTML code snippet: <!DOCTYPE html> <html> ...

Comparing the use of input parameters to pass information in node.js versus the use

I'm grappling with the concept of when to inject a response into a function or call a function and retrieve something from it. Specifically in Node.js. Do functions in Node.js actually return data, or is it primarily about passing arguments and utili ...

Is there a Javascript library available that can generate calendar links for Google, Yahoo, Outlook, and iCal?

I recently came across a sleek and professional web page widget that includes links (for example, and meetup.com). Could someone assist me in finding the library responsible for creating these links? I explored the discussion on Need a service that build ...

I am a beginner in the world of MEAN stack development. Recently, I attempted to save the data from my form submissions to a MongoDB database, but unfortunately, I have encountered

const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); const Schema = new mongoose.Schema({ username: St ...

Is it achievable to employ the object "angular" while still implementing the 'use strict' directive?

Whenever I use gulp-jshint, it requires me to include the 'use strict' directive in every file. This causes an issue with my global object emApp, defined in my app.js file as: var emApp = angular.module('emApp'); Interestingly, jshint ...

The i18next plugin initialization does not include the implementation of 'resGetPath'

I'm having trouble setting up the resGetPath attribute in i18next to access translation.json files locally. When I initialize the plugin with the resources object, everything works fine. However, when using the resGetPath attribute, I can't seem ...

Uploading images seamlessly through ajax

Despite the abundance of tutorials, I am struggling to make them work. In my input form for file upload, I have: <input onChange="userPreviewImage(this)" type="file" accept="image/*" style="display:none"/> Here is my Javascript code: function use ...

Provide alternative styling through css in instances where the Google Books API does not provide an image

How can I modify the CSS code to display the author and title of a book when there is no image available from the Google Books API? Currently, users see a custom image linked here, but it's not clear what it represents without the name and author inf ...

Firebase Hosting integrated with Cloud Functions

Struggling with deploying my functions and hosting. While I have managed to get them working separately on different branches, integrating both hosting and cloud functions is proving to be a challenge. It seems like my cloud function is not deploying succ ...

Utilizing vue-chartjs to display a pair of data figures side by side

In my vue application, I utilize vue-chartjs to showcase some data and I incorporate semantic-ui for the layout. My goal is to display two figures side by side on the screen, but unfortunately, I am facing difficulties achieving this. I have attempted us ...

Material-UI is having trouble resolving the module '@material-ui/core/styles/createMuiTheme'

Although I have searched for similar issues on StackOverflow, none of the solutions seem to work for me. The errors I am encountering are unique and so are the fixes required, hence I decided to create a new post. The company conducting my test provided m ...