Random Post Inside Modal using BricksExtras

In the BricksLabs Facebook group a user asks:

So I have a modal, that opens with a random post title and content from a custom post type. I have a button underneath that I would like people to click that would then refresh the post displayed above to a different random post.

To do this without page refresh we need to use AJAX or REST API as far as I know.

What can be done in Bricks without writing code though, is using the Modal element of BricksExtras and using its multiple triggers feature: one when the button is clicked and another on page load when it has a URL parameter like show=another.

We then add a onclick attribute to the button inside the Modal to reload the page and when the page reloads the modal will auto-open showing a random (usually different) post.

Step 1

Install and activate BricksExtras. Enable the Modal element in its settings.

Step 2

Edit your template/Page with Bricks.

Add a Button having a text like “Show Post”.

Set it to link to an external URL of #.

Go to STYLE tab and give it this CSS ID: modal-trigger.

Step 3

Add a Modal element at the root level of your page structure near the bottom.

We are going to add two triggers.

Trigger type: On click element
Element selector: #modal-trigger

Trigger type: On page load (Incl. URL parameter)
URL parameter includes: show=another

Note: The above URL parameter can be any of your choice. Ex.: load=random. You need to set the same (with a ? at the front) as the link for the button inside the modal in a later step.

Step 4

Add a Container inside the Modal and a Block inside it.

Enable Query Loop on the Block and set it to output 1 random post of your desired post type.

Add Post Title and Text elements inside the Block. Delete the default text of the Text element and insert the Post excerpt dynamic data.

Add a Button under the excerpt text element.

Change its text to something like “Show Another Post”.

Link type: External URL
URL: ?show=another

Go to STYLE tab > ATTRIBUTES and add this attribute:

Name: onclick
Value: window.location.reload()

That’s it.

With this in place, on the initial page load, the modal appears when the #modal-trigger button is clicked. The modal shows the info of a random post. When the button inside the modal is clicked, the page will reload and go to whatever is the current page URL plus ?show=another at the end. Since we have also set the corresponding URL trigger in the modal, it will appear as soon as the page reloads showing another random post.

Thanks to Maxime Beguin for sharing the line of JS for reloading the page.

Leave the first comment