niceoneishere
niceoneishere

Reputation: 343

execute php code in wordpress text widget

I am trying to execute a if condition in text widget. I added this to my theme function file

function execute_php($html){
 if(strpos($html,"<"."?php")!==false){
      ob_start();
      eval("?".">".$html);
      $html=ob_get_contents();
      ob_end_clean();
 }
 return $html;   

} add_filter('widget_text','execute_php',100);

but when I write a php condition like this it throws an error at line 90 which eval("?"."?".$html) and here is the exact error

Parse error: syntax error, unexpected '{' in /functions.php(90) : eval()'d code on line 13

here is the condition I am writing

    <?php if (is_post(43)) { ?>
 <div class="book">
  <a class="button" href="/product1">Buy Now</a>
 </div>
<?php } elseif (is_post(37)) { ?>
  <div class="book">
  <a class="button" href="/product2">Buy Now</a>
 </div>
<?php } elseif (is_post(30)) { ?>
 <div class="book">
  <a class="button" href="/product3">Buy Now</a>
 </div>
<?php } else (is_post(24)) { ?>
  <div class="book">
    <h5>Buy Now</h5>
    <select class="sportsman-colors" onchange="document.location.href=this.value">
     <option value="-1" selected>Choose Color</option>
     <option value="/product4">Green</option>
     <option value="/product6">Red</option>
    </select>
 </div>
<?php } ?>

Can someone please tell me where I am making a mistake. I am closing all the tags

Thanks

Upvotes: 0

Views: 1705

Answers (2)

Suraj
Suraj

Reputation: 11

If you want execute php code into wordpress widget then simply change following code into theme function file

add_filter('widget_text','execute_php',100);
function execute_php($html){
     if(strpos($html,"<"."?php")!==false){
          ob_start();
          eval("?".">".$html);
          $html=ob_get_contents();
          ob_end_clean();
     }
     return $html;
}

You can read more expiation on http://www.helpersways.com/2015/09/use-php-code-in-wordpress-widget-without-plugin.html

Upvotes: 1

Jonathon
Jonathon

Reputation: 113

You could instead use a plugin like Widget Logic and add your conditions like is_post(24) under separate text widgets

Upvotes: 0

Related Questions