Steps to dynamically fetch only the main content of a wordpress post with ajax

Utilizing ajax for loading a new post in WordPress is quite simple. Below is the basic code snippet to achieve this:

function loadNewPost(){
    var menuitem = document.getElementsByTagName('nav')[0].childNodes;
    for(var i= 0; i < menuitem.length; i++)
    {
        bindEvent(menuitem[i], "click", loadAjax);
    }
};

function loadAjax (event) {
    event.preventDefault();
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange  = function(){
        var content = document.getElementsByTagName('article')[0];
        if(xhr.readyState  == 4){
            if(xhr.status  == 200) {
                content.innerHTML = xhr.responseText;
            } else{
                content.innerHTML = 'Failed to establish connection with the server. Please check your internet connection.'
            }
        }
    };
 
    xhr.open('GET', this.href, true);
    xhr.send();
}

bindEvent(window, "load", loadNewPost);

The above code functions well but loads the entire new post along with menu, header, and footer elements. I am interested only in extracting the main content and comments. Is there any way to specifically request these specific contents from WordPress using ajax? Or do I have to retrieve the entire page and then filter out the required content before displaying it?

Perhaps creating a custom template page could be a solution. However, I am unsure how to implement this. Any guidance on configuring that would be appreciated.

I hope my query was clear. It's my first attempt at developing a WordPress theme using PHP.

Thank you for your assistance!

Answer ā„–1

Using a template may seem like a good idea, but creating your own could be challenging and intricate. Andrew M.'s suggestion about using jQuery is accurate, as it allows you to download only specific parts of a document instead of the entire thing. Refer to the section on loading page fragments for more information, but for quick reference:

$('#result').load('ajax/test.html #container');

This code snippet will fetch test.html and inject the content of its #container element into the #result element on the main page with ease.

Note that while this method may still consume server resources and bandwidth similar to rendering the complete page, assets like images will only load if they are within the requested segment. Unless you have exceptionally high traffic levels, this extra workload shouldn't pose a significant concern.

If your goal is to minimize the initial data sent by the server, the approach you take will hinge on additional requirements related to your WordPress setup.

In scenarios where you merely need to display one specific page without direct human access, a straightforward solution involves creating a minimalist template:

while ( have_posts() ) : the_post();
  echo '<h2>';
  the_title();
  echo '</h2>';
  the_content();
endwhile;

All you have to do then is assign this custom template to the relevant post.

However, if users must view the post on the original page as well, implementing a custom theme with a singles template alongside a theme switcher plugin becomes necessary. Moreover, you'll need to adequately configure your AJAX request to trigger the use of the machine-readable theme, making the process relatively more intricate.

Answer ā„–2

Upon my arrival here, I was seeking a solution similar to the one put forth by the OP [cmplieger].

In the past, I have utilized the technique outlined by sudowned to create a WordPress theme. The page implemented header detection, loading headers and content as needed, and even optional footers. It truly is an efficient theme that loads with impressive speed. This method is undoubtedly the most effective...

However...

While I highly recommend sudowned's approach, I had a thought about creating something that functions solely on the browser side. Hence, this post motivated me to devise a new method:

Note: This may not be my preferred way of doing things. I would still lean towards sudowned's suggestion above. Nevertheless, there could be scenarios where this alternative comes in handy.

And so...

/* jQuery must be included */
// Assumptions:
// - jQuery is being used
// - Pages being called are within the same domain as the calling page
// 

A snippet of HTML:

<div id="content">
        <div id="list">
         <ul>
          <li name="//fiddle.jshell.net/isme/j4ygp3nn/show/">Page 1</li>
          <li name="//fiddle.jshell.net/isme/gmvj0ohg/show/">Page 2</li>
        </ul>
       </div>
     </div>

A touch of CSS:


    #list ul {  list-style-type: none;}
    #popc {  margin-top: 20px;  margin-left: 20px;}
    #list ul li {  text-decoration: underline;  color: #343434;
    margin-bottom: 5px;  cursor: pointer;}
    #popcontent {  background: #ffffff;  border: 1px solid #000000;
    width: 80%;  min-width: 80%;  margin-left: auto;
    margin-right: auto;  height: 80%;  min-height: 300px;
    position: absolute;  display: none;  top: 10%;  left: 10%;
    border-radius: 12px;}
    #x_it {  text-align: center;  float: right;  width: 17px;  border: 
    solid 2px #000000;  color: #000000;  background: red;
    border-radius: 12px;  padding-left: 0px;  padding-right: 1px;
    padding-top: 2px;  padding-bottom: 0px;  margin-right: 10px;<br>
    font-family: sans-serif;  font-weight: bold;  cursor: pointer;}

Add some jQuery magic:

   jQuery("#content").after("\  
      <div id=\"popcontent\">\  
           <p id='x_it'>X</p>\  
 <div id='popc'></div></div>");  

   popc = jQuery("#popc");  
   popcontent = jQuery("#popcontent");  
  jQuery("#x_it").click(function() {  
     popcontent.fadeOut("fast");  
   });  

jQuery("#list ul li").click(function()  
                                 {  
                     popc.html("");  
                     popc.load(jQuery(this).attr("name") + \  
                     " #main_content");  
                     popcontent.fadeIn("fast");  
                                 });  

`

I have shared a functional demo on fiddle: https://jsfiddle.net/isme/jjok5kus/34/

The key element here lies in the load call.
The second argument being "#main_content" instructs the load function to specifically load that element into your chosen div. Refer to the documentation for jQuery.load()

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

Encountering error notifications when attempting to install Node npm

Iā€™m currently in the process of setting up these npm packages: npm I express body-parser bcrypt cors dotenv gridfs-stream multer multer-gridfs-storage helmet morgan jsonwebtoken mongoose Regrettably, each time I try to download them, an error seems to o ...

When I try running my JavaScript code in the console, it works perfectly fine. However, I encounter an error when I attempt

Recently, I added a cool JavaScript code to my website that changes the background of the landing page randomly. Here is the snippet: var bgImages = [ "url('assets/bg/front1.jpg')", "url('assets/bg/fro ...

Tips for updating an input field using JavaScript

Here is a simple code snippet that I have written. <script language='javascript"> function check() {} </script> <div id="a">input type="text" name="b"> <input type="button" onClic ...

Angular2 - Actively selecting a checkbox in an ngFor loop with a reactive form

There is an object retrieved from a database that consists of a list of names with their corresponding IDs, as well as a flag to indicate whether they are selected or not. Object: let items = [{ ID: 1, Name: 'Item A', Selected: 'Y ...

Checking for date overlap between two textboxes in MVC5 when searching against a date field

Currently, I am exploring options to implement search filters for my model results. I have a field called RunDate and I intend to allow users to search between two dates using two textboxes. @Html.TextBox("StartDate", null, new { @class = "datefield form- ...

Can OR be utilized within a find operation?

I am currently developing a social media platform similar to Facebook using Express and MongoDB. One of the features I'm working on is adding friends to user profiles. When a user clicks on a button that says "Send Friend Request" on another user&apos ...

Unable to initialize a variable from a JSON/jQuery object

I am successfully able to retrieve my AJAX request, but I'm facing an issue with my jQuery code once I declare a variable from it. Below is the JSON response obtained from the console: Object {readyState: 4, responseText: "{"rsp":"1","msg":"show out ...

Stretch background image with html2Canvas in Chrome

I am currently using html2canvas to generate an image of a canvas with a background. It is working fine in Firefox, but in Chrome, the background is being vertically stretched. I am unsure of what the issue may be. Here is the link to my fiddle: http://j ...

"Utilizing jQuery to present the accurate sequence within a table

https://i.sstatic.net/iCpnO.png I am currently experiencing an issue with my JavaScript code. I am trying to display a single column for "Success/Fail" in a table, but it is showing as two separate columns. The values for the "Success/Fail" column are not ...

Troubleshooting jQuery draggable issues with overflow and unordered list elements

Recently, I've been organizing my folder and file system and I wanted to implement a drag-and-drop feature to move items between folders and locations seamlessly. Although I have successfully enabled dragging functionality, I am facing an issue with ...

Warning message prior to making Ajax call in a series using JQuery

I'm currently working on implementing a loop that prompts the user for confirmation before making a synchronous ajax request, but I'm encountering some issues. Here is my code snippet: <script> $(document ).ready(function() { f ...

Creating a JSON array in JavaScript: A step-by-step guide

Presently, I am engrossed in a project involving the creation of a Box and Whisker Plot. The data for this task is being sourced from a PHP file and then passed on to a JavaScript function for the actual Box and Whisker Plot generation. In my possession, t ...

Having trouble loading texture locally in THREE.js?

Here's the scenario: I have a local file where I attempt to load a texture using the following code: var texture = THREE.ImageUtils.loadTexture( 'image.jpg' ); var cubeGeo = new THREE.CubeGeometry( 50, 50, 50 ); var cubeMat = new THREE.Mesh ...

When you download a file through the unpkg CDN, the size of the npm package is

I am experiencing a discrepancy with the file size of a file in my npm package. The file is 307kb in size, but when I download it through unpkg, the same file is only 73.2Kb. I find it quite puzzling how the file can be smaller when downloaded over the net ...

Automating testing with WebdriverIO in scenarios where JavaScript is turned off

Is it possible to launch the browser with JavaScript disabled in the WebdriverIO framework? I am looking to automate a scenario that requires JavaScript to be disabled. However, when I try to disable JavaScript manually in Chrome or Firefox and run WDIO s ...

Clear v-model without changing its associated values

I'm facing an issue with my <input> fields, which look like this: <input type="text" v-model=user.name" /> <input type="text" v-model="user.phone" /> <button @click="add">add user</button> Whenever the add user button i ...

Error in Jquery: Unable to locate element with attribute "[data-weight]"

After removing a lot of unnecessary code for better readability, I encountered an error on this line: $('[data-weight]').each(function() { The error message indicates that it is null <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "h ...

Managing Multiple File Inputs in React Using useRef Array Results in an Undefined Value

In the process of developing a React application, I encountered an issue where multiple file input elements were dynamically rendered using the Swiper component and Dropzone. However, upon attempting to retrieve all the selected files from these inputs dur ...

Vue.js blocks the use of iframes

I've come across a peculiar issue where I need to embed an iframe inside a Vue template and then be able to modify that iframe later. The code snippet below shows the simplified version of the problem: <html> <body> <div id="app" ...

My string is being cut off due to the HTML value

My webpage utilizes HTML5 to enable file uploads directly from the browser. The uploaded file is a PDF that needs to be displayed within an <input type="text"/> The following is my code snippet: var files = evt.target.files; // FileList object // ...