1

I am creating a WordPress plugin where a user can specify a custom loop repeater based on the value of a textarea.

The idea is, a user can use a predefined repeater that ships with the plugin or they can build their own repeater by simply adding html + PHP to the textarea.

Example of a custom repeater:

<h1><?php the_title(); ?></h1> <?php the_excerpt(); ?> - <?php the_time(); ?>

The issue is when I echo/print the textarea value, the WordPress functions within the <?php ?> tags do not execute.

Is what I'm attempting even possible?


Let me explain further... I am building an installable plugin based on my Ajax Load More script. This plugin will be only used by site admins and for total control of the display of posts I want to allow them to create a custom repeater.

On the plugin settings page, I want to have a textarea where the admins can add whatever html/php code they want in order to customize the repeater.

My issue is how do I execute the PHP entered within the textarea on the frontend as echoing the value does not work.

mleko
  • 11,650
  • 6
  • 50
  • 71
Darren Cooney
  • 1,012
  • 16
  • 25

3 Answers3

2

Use eval function to change plain text to php code. More about it here

eval('echo "Hello world!"'); 

will print out "Hello world!" instead of 'echo "Hello world!"'

BUT what if i write to textarea:

die();
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • `eval` can be quite dangerous. However, there are other ways to get to the same goal, as leri explaned here quite lengthy: http://stackoverflow.com/questions/17672183/eval-does-not-return-the-function-results/17672269#17672269 – Tate83 Jun 03 '14 at 10:56
1

One way of doing this is to use the eval() function as Justinas says, but I would strongly recommend you don't use it as I have found it to be unreliable and problematic.

What I would recommend is to write the PHP code in the string you extract from the text area to a file and then include that file where you want the PHP to execute.

So, I would recommend running

<?php file_put_contents($file_path, $contents); ?>

whenever the text area is updated to update the file, then

<?php include_once($file_path); ?>

where you want the code on the front end.

Harri Bell-Thomas
  • 674
  • 1
  • 7
  • 18
  • thanks. This is exactly the approach I have taken. Works perfectly once written to a php file and then included in the loop. – Darren Cooney May 30 '14 at 17:08
-1

Those wordpress functions will not work unless they are in the Loop, Here is a basic Loop:

 <?php if(have_posts()) { ?>    
 <?php while(have_posts()) { ?> 
 <?php the_post(); ?>   
 <?php // custom post content code for title, excerpt and featured image ?> 
 <?php } // end while ?>    
 <?php } // end if ?>
DannieCoderBoi
  • 728
  • 2
  • 12
  • 31