Run PHP code in a WordPress widget
February 2, 2014 Leave a Comment
I had an advertiser who wanted his link to appear in the right sidebar of the site, but only on the home page of site. Sidebar widgets usually appear throughout the site, so I had to figure out how to make it work.
I knew WordPress supported an
is_home() conditional statement, but PHP code can only be executed in themes and plugins, not in free text/HTML. I tried inserting the code into the functions.php code, but never got it to work exactly right.
It turns out there’s a WordPress plugin called PHP Code Widget that lets you execute PHP code inside a widget. Just type it in along with your text and HTML and it works. Here’s the code:
<?php if( is_home() ) : ?>
Text and HTML go here and will appear only on the home page.