Discover with this tutorial how to insert a conditional widget on the page of your choice in WordPress without plugins.
Following the tutorial where I explained how to create a new widget area in Genesis Framework, a subscriber asked me:
Greetings, Nahuai.
Thank you for this post, I find it very useful.
One question: Is it feasible to put conditional widgets?
I mean, if we want them to be seen in a certain tag only or in a certain page, not in the whole template.Thanks!
Interesting, isn’t it?
In this case, you are going to learn how to show a widget on a certain page.
With this base you will be able to make small changes to suit your specific needs.
Steps to display a widget only on a WordPress specific page
1. Get the widget’s ID displayed
First you need to know the ID of the widget you want to conditionally display.
But, by default, the box where you fill in the widget content does not show the ID of the widget in question.
To change this situation, add the following snippet to the end of the functions.php file or to your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
It’s as simple as that. From now on, this is what you will see when you enter the widget edition:
In this case, the ID is “enews-ext-2”
2. Load the widget only in the page you want
Now that you know the widget ID, you can use conditional logic on it.
In this case, you will use the conditional tag is_page() with the page ID number.
Add the following code at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
With this simple snippet you tell WordPress that, if it is not the page you have selected, it should not load that particular widget.
In this case, the widget would load only on the page with ID 1390, but I invite you to modify the code with the one you are interested in.
You can get the ID of the page by checking the URL when you edit it or, if you want to make it easier for yourself, get it to be displayed directly in the WordPress admin with this tutorial.
Conclusion
With a few lines of code you can know the widget ID and conditionally display it on a specific page.
This is just an example of what you can achieve by knowing the ID of a widget and using conditional tags.
I hope it inspires you. 🙂
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉