Post Content in Offcanvas using AJAX in Bricks

Updated on 14 Feb 2024

This Pro tutorial provides the steps to set up a list of posts whose titles which when clicked shows that post's title, featured image and content in an offcanvas in Bricks builder.

We shall use AJAX to dynamically fetch the clicked post's data and load it in the offcanvas with a loading indicator appearing initially.

Note: The steps below need you to use a child theme. While it may be possible to implement this tutorial using a plugin like WPCodeBox, that is not covered.

Also, it is much easier to implement the same using BricksExtras. See this.

Intro

Here's the overall picture:

  1. We create a section-type of Bricks template called "Offcanvas Post Content". Inside this, we place the elements that should appear for each post. Ex.: Post Title, Image (set to featured image) and Post Content.
  2. We create a Page having a Bricks Query Loop that pulls the latest 5 posts. Each loop item contains a Basic Text element with a data attribute = the post ID.
  3. User clicks on the post link.
  4. Our JavaScript code executes vanilla JavaScript equivalent of ajax() function using a) the URL to the file in WordPress AJAX API responsible for handling AJAX requests and b) URL of the loading indicator image passed to it from PHP.
  5. Request gets sent to admin-ajax.php.
  6. admin-ajax.php looks at the registered action and runs the function hooked to this action. Inside the function we write PHP for outputting the clicked post's content incl. any CSS that Bricks generates for the section-template.
  7. The response gets sent back to JavaScript and we display that on the front end.

Step 2

If you aren't already using it, download, upload and activate Bricks child theme.

It will not affect the functionality of your site if it has been built without a child theme.

Create a directory called assets.

Inside the above, create directories having these directories: js, img

Like this:

wp-content/themes/bricks-child
-- assets
------ js
------ img

This is a BricksLabs Pro tutorial.

For full access login below or create your BricksLabs Pro account

Instant access to 390+ Bricks code tutorials with BricksLabs Pro