You are here: Home / Wordpress Plugins / Allow PHP in Posts and Pages

Allow PHP in Posts and Pages

Allow PHP in posts and pages adds the functionality to include PHP code in WordPress posts and pages by adding a simple shortcode [php].code.[/php]

This plugin attempts to strip away the automatically generated wordpress <p> and <br/> tags but still allows the addition of your own <p> and <br/> tags using a form of BBcode items such [p][/p] and

You can also save your most used bits of code as snippets for use across multiple pages.

With Version 2.2, the older tag replacement system has been revamped, hopefully reducing the need to escape some characters for example: [ and ] that shouldnt be changed < and >

With Version 2.3 comes an experimental advanced filter feature which allows you to use standard php code while taking advantange of variables thoughout the entire post content, and functions, as well as no pesky tag replacement.

With Version 3 comes entirely re-written code with support for code snippets being used in conjunction with the advanced filter feature as well as a class variable to share variables between saved snippets and code blocks. This version also comes with UI updates.

Usage

Using the plugin couldn’t be simpler; the plugin has 2 variants of shortcode available, [php] and [allowphp] other versions of the shortcode may exist but are not fully supported.

To add the PHP code to your post or page simply place any PHP code inside the shortcode tags.

The shortcode can take a some additional attributes to assist with PHP writing

  • “debug” – [1/0] – Turns on error reporting and display errors for snippets
  • “silentdebug” – [1/0] – When used with “debug” shows errors in the source code only
  • “mode” – ["old"/"new] – Maintained for backwards compatibility only – When set to “old” enables the pre version 2.2.0 code replacement system for that shortcode, when set to “new” with the preparse option enabled it uses the newer code replacement system for that shortcode

Code Snippets

In addition to these attributes, a new one has been added called “function”. The function attribute allows the addition of user defined code snippets into the content. The shortcode for snippets is [php function=x] or [allowphp function=x]

To integrate the snippets with the advanced filter, the shortcode should not contain any additional attributes or spaces

Code snippets can be added in the plugin’s options page and can be re-used on as many pages as you like

Advanced Filter

The advanced filter is the newest feature of the plugin.

It allows the user to write standard html directly into the html post editor without needing tag replacements.

There are 2 ways to enable the Advanced Filter, the easiest way is to enable it in the plugin options page, the other way is to add “useadvancedfilter”onto the standard shortcode to use it on a shortcode by shortcode basis:

[php useadvancedfilter]...[/php useadvancedfilter] or [allowphp useadvancedfilter]...[/allowphp useadvancedfilter]

Vairable Sharing

The plugin class contains an array with can be used to share variables around the page, between blocks of php code anywhere.

Variable delarations can be made by accessing the global variable $allow_php as follows:

[<span></span>php]
	global $allow_php;
	$allow_php-&gt;_shared['my_key'] = 'my value';
[<span></span>/php]
<em>This code will set "my value" to index "my_key" within the shared array</em>
[<span></span>php]
	global $allow_php;
	echo $allow_php-&gt;_shared['my_key'];
[<span></span>/php]
<em>This code will output the index "my_key" within the shared array</em>

This can be useful for passing post information to the sidebar :)

Some Important Notes

This plugin strips away all instances of <p> and <br /> therefore code has been added so that if you wish to use tags in your output (e.g.):

[<span></span>php] 
	echo "hello &lt;br /&gt; world"; 
[<span></span>/php]

The < and > tags will need to be swapped for [ and ] respectively so <p> becomes [p] and </p> becomes [/p] which is converted back to <p> at runtime. these [ ] work for all tags (p, strong, em etc.).

[<span></span>php] 
	echo "hello 
world"; [<span></span>/php]

With code written pre-version 2.2.0 you may need to turn on support for the older replacement method as you may experience issues with the code being disrupted as the replacement method has been changed, however you can set the tag replacement method to be the older version in the plugin options or by adding mode=old to the [php] tag, similarly, if you wish to use the new method when you have the old method turn on in the plugin options, just add mode=new to the [php] tag. In the current release, only known html tags are altered by the code, other tags and square bracket items (such as PHP arrays) are no longer affected.

The code replacement method isn’t always perfect however, as certain items such as arrays cannot be accessed during echos and will need to be set as a variable before echo (this doesn’t apply to the advanced filter)

echo "[p]".$myArray[0]."[/p]"
	<em>as</em>
$mya = $myArray[0];
echo "[p]".$mya."[/p];

Comments

  1. Can this php be connected to a database on the same server but not the one automatically constructed by the wordpress installation?

    • Hi Dave,
      Yes it can automatically connect to a database, simply use the mysql_connect() function or the mysql_pconnect() function.

      [php debug=1]
      mysql_pconnect(“database host”,”username”,”password”);
      mysql_select_db(“database”);

      [/php]
      Just make sure to turn off debug when you set the page to be live or it will also output your database access details!

      • Is there a security concern with putting in the username and password with no encryption? Is the code exposed in the page?

        Sorry, I’m kinda new to this!

        • Hi Frankie,
          Yes the details are put into the database, but you can also put it into an external php file and include that by doing include (‘filepath’) ; or require (‘filepath’) ; without the spaces.

          Jamie

      • Hey there!

        Thanks for that great plugin. Most stuff is fine. But:

        I try to do this:

        [php]

        $mysqlhost=”localhost”; // MySQL-Host angeben

        $mysqluser=”localadmin”; // MySQL-User angeben

        $mysqlpwd=”eleVen.14″; // Passwort angeben

        $connection=mysql_connect($mysqlhost, $mysqluser, $mysqlpwd) or die (“keine Verbindung möglich.
        Benutzername oder Passwort sind falsch. Grund: $connection “.mysql_error());

        $dbselection = mysql_select_db(“kerwe”)
        or die (“Die Datenbank existiert nicht.”);
        if ($dbselection == TRUE)
        {
        }
        else
        {
        die (“Leider ist bei der Datenbankabfrage schiefgelaufen. Bitte versuche es zu einem späteren Zeitpunkt noch einmal.”);
        }
        $query = “SELECT
        day_db,
        date_db,
        carrier_db,
        place_db,
        pp_db
        FROM program ORDER BY date_db LIMIT 50″;

        $result = mysql_query($query)
        OR die(“Error: $query “.mysql_error());
        $number = mysql_num_rows($result);
        [/php]

        Tag

        Zeit

        Verein

        Ort

        Programmpunkt

        [PHP]
        while($row = mysql_fetch_array($result))
        {
        $rowdate = $row['date_db'];
        $split_rowdate = explode(” “, $rowdate);
        $time = $split_rowdate[1];
        [/PHP]

        [PHP]
        echo $row['day_db']; <———
        [/PHP]

        [PHP]
        }
        [/PHP]

        and get that:

        Parse error: syntax error, unexpected $end in C:\xampp\htdocs\wordpress\wp-content\plugins\allow-php-in-posts-and-pages\allowphp.php(110) : eval()’d code on line 7

        Parse error: syntax error, unexpected ‘}’ in C:\xampp\htdocs\wordpress\wp-content\plugins\allow-php-in-posts-and-pages\allowphp.php(110) : eval()’d code on line 2

        with an empty table (of course except of the -cells).

        What is the problem? I marked the problematic row in here with “<——". This row will echo five times with other vars. I'm driving crazy! Please help me… After this I see the next two posts containing "it's not working with array refs". Is there a kludge?

        • Oh, unfortunately I see the “less-than” and “more-than” signs have been erased in here.

          Actually the problem row is:

          “less-than sign”td”more-than sign”[PHP]=$row['day_db'][/PHP]“less-than sign”td”more-than sign”

          I just tried to replace the “=” with an “echo”.

          I hope, everything was understandable?

  2. it’s not working properly with array refs.

    I want to get a value from $_GET['xyz']

    either [ and ] are translated to HTML Entities, or

    • Hi David,
      I have looked into this and the second square bracket is not translating back properly just now, A new version is ready to be released and should hopefully be up by Monday. Thankyou for bringing this problem to our attention

      Jamie

      • This bracket parsing problem still persists, I have the code:

        if($_REQUEST['subin']){

        which gets parsed and errors as:

        Parse error: syntax error, unexpected ‘>’ in allow-php-in-posts-and-pages/allowphp.php(50) : eval()’d code on line 4

        ////*********************** Search Results section.*******************************************************************
        error_reporting(0);
        if($_REQUEST){

        Is there any plan to fix the bracket problem, or can it be fixed by escaping the brackets?

        • Hi Sam,

          It can currently be fixed by escaping brackets, we are still looking into the best way to over come this issue without resulting to removing the visual editor.

          In the mean time, the code snippet can be used for a tidier post editing screen, and doesn’t require the escaping part :)

          Thanks,
          Jamie

  3. I have this in wordpress, and am trying to embed the sum of a column from a separate table.

    I am getting the following error: Resource id #118

    mysql_pconnect(“localhost”,”username”,”password”);
    mysql_select_db(“database”);
    $query_SumDonors = “SELECT Sum(hkm_donors.Paid) AS SumPaid FROM hkm_donors”;
    $SumDonors = mysql_query($query_SumDonors);
    echo $SumDonors;

    why doesn’t this work?

    • Hi Justin,

      Thank you for your comment,
      1 | mysql_pconnect(“localhost”,”username”,”password”);
      2 | mysql_select_db(“database”);
      3 | $query_SumDonors = “SELECT Sum(hkm_donors.Paid) AS SumPaid FROM hkm_donors”;
      4 | $SumDonors = mysql_query($query_SumDonors);
      5 | echo $SumDonors;
      In this case Resource id #118 is not an error, it is a resource returned from the database query,
      To access this resource you need to call mysql_fetch_row($SumDonors) before you echo $SumDonors.

      1 | mysql_pconnect(“localhost”,”username”,”password”);
      2 | mysql_select_db(“database”);
      3 | $query_SumDonors = “SELECT Sum(hkm_donors.Paid) AS SumPaid FROM hkm_donors”;
      4 | $SumDonors = mysql_query($query_SumDonors);
      5 | $SumDonors = mysql_fetch_row($SumDonors);
      6 | echo $SumDonors[0];

      This new code fetches the first row of the query results, then outputs the first column of the row (which contains SumPaid).

      I hope this helps,

      Jamie

  4. Hi

    I seem to be going around in circles at the moment trying to get this to work.

    I am posting some variables to a wordpress page

    http://www.unifastnews.co.uk/form-test?product=Kaptinut&fromURL=http://www.unifastnews.co.uk/archives/33&toURL=http://www.unifastnews.co.uk/?page_id=36

    But the code I am embedding get messed up, so I am not sure if this would work in the first place

    [php debug=1]
    $product = $_POST\['product'\];
    $fromURL = $_POST\['fromURL'\];
    $toURL = $_POST\['toURL'\];
    echo ”;
    echo ”;
    echo ”;
    [/php]

    gets changed to :-

    $product = $_POST['product'];
    $fromURL = $_POST['fromURL'];
    $toURL = $_POST['toURL'];
    echo ‘ ‘;
    echo ‘ ‘;
    echo ‘ ‘;

    Thanks

    Dave

    • looks like the form inputs have been stripped from the code feel free to look at the site

      Dave

      • Hi David,

        After looking at your page it appears that the single quotes are breaking it, an update has been made to fix this solution, if you can update then try it.

        Thanks
        Jamie

        • Hi Jamie

          I have problem to get this lines to work:
          [php debug=1]
          $first = $_POST\['first'\];
          echo $first;
          [/php]

          The code from the form page is:

          First Name:

          Can you give me an idea how I can handle this?

          Best regards
          Peter

          • Hi Peter

            It appears WordPress has stripped out some of the code you provided.
            Can you please email me the code in relation to the below to help us find the problem

            The code from the form page is:

            First Name:

            Can you give me an idea how I can handle this?

            Best regards
            Peter

            Thanks
            Jamie

  5. Can the plugin be used to conditionally use short codes from other plugins? I have a case where I’d like to display a different short code button from the WP Utility Shortcodes plugin depending on whether or not the user is logged in. When I echo the short code it doesn’t get evaluated and shows up as text. Any direction / help you can give me? Thanks in advance.

    • Hi James,

      Yes this plugin can be used for a conditional shortcode.

      the code for your particular question would look something like:

      [php]
      if(is_user_logged_in()){
      do_shortcode(‘shortcodename’);
      }
      else {}
      [/php]

      Thanks
      Jamie

      • Feel like I’m really close but can’t quite get it to work. However in debug mode I do see the output but I must have something wrong still.

        The short code I want to use as it is given to me by the plugin is (Contact Form 7):

        [contact-form 1 "Citations Submission"]

        The code I’m trying is:

        [php]
        if(is_user_logged_in()){
        echo “hello”;
        }
        else {
        do_shortcode(‘\[contact-form 1 \"Citations Submission\"\]‘);
        }
        [/php]

        And I get nothing, however, as I said, the shortcode’s comment form shows up with the debug output. I’ve tried various combinations of escaping brackets, quotes, and exchanging double quotes for single etc.

        Sorry, my php mojo is pretty weak. Any suggestions? Thanks.

  6. Hi, Jamie Fraser.
    Your plugin will not work, I made screenshots. In what may be the problem? WordPress 3.0
    first screenshots – http://www.imget.ru/images/2010/12/05/qPwJlAEybi.jpg
    second screenshots – http://www.imget.ru/images/2010/12/05/CPbIn9zZCa.jpg

    Thanks in advance.

    PS: sorry for my bad english, I’m from Russia.

  7. Hi !

    I just tried your plugin and had some problem with getting the result of an HTTP call. Here’s my code :

    [php]
    if( !class_exists( ‘WP_Http’ ) ){
    include_once( ABSPATH . WPINC. ‘/class-http.php’ );
    }
    $request = new WP_Http;
    $result = $request->request( ‘http://www.site.com/’);
    echo $result\['body'\];
    [/php]

    I Had to escape the brackets of $result['body'] in order to display it properly, just wanted to let you know about this!

    • Hi Anthony,

      Thank you for your comment,
      We were aware of the escaping of the square brackets being necessary, its documented in the readme file.

      We are looking into solutions to avoid escaping however.

      Thanks
      Jamie

  8. Any idea why tags are stripped from the output of this code:

    [php]
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=5');
    while ($recentPosts->have_posts())
    {
    $recentPosts->the_post();
    echo '[li][a href=\'' . the_permalink() . '\']' . the_title() . '[/a][/li]';
    }
    [/php]

    • Hi Testing,
      you should not echo “the permalink()” and the_title() because they automatically output their results, split your code up to be like the following:
      [php ]
      $recentPosts = new WP_Query();
      $recentPosts->query(‘showposts=5′);
      echo “[ul]“;
      while ($recentPosts->have_posts())
      {
      $recentPosts->the_post();
      echo ‘[li][a href="';
      the_permalink();
      echo '"]‘;
      the_title();
      echo ‘[/a][/li]‘;
      }
      echo “[/ul]“;
      [/php]

      Thanks
      Jamie

      • I tried this exact copy and paste code, and got:

        Parse error: syntax error, unexpected ‘=’ in /home/bioglug/public_html/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(77) : eval()’d code on line 3

        • Hi Eric,

          Which exact code are you meaning?

          Have you tried the debug feature?

          Thanks,
          Jamie

          • This is my solution

            [php]
            global $post;
            $args = array( ‘numberposts’ => 5);
            $myposts = get_posts( $args );

            foreach( $myposts as $post ) : setup_postdata($post);
            echo ‘[li]<a href=”‘;
            the_permalink();
            echo ‘”>’;
            the_title();
            echo ‘[/a][/li]‘;
            endforeach;
            [/php]

  9. Hi, it’s not working at all for me so I’m sure I’m doing something wrong.
    1) Downloaded and installed and Activated it. I get the nice Settings page.
    2) Put the [php] phpinfo(); [/php] in the HTML of my page.
    3) I get nothing.

    BTW, I want to invoke the wp_loginout() function on my page.

    Thanks for all your work.

    • Hi Mike,

      After much work on this, i have found that there appears to be an issue with your installation because upon visiting your site i can see the phpinfo() output.

      This has been a strange case indeed.

  10. The website above is just for code dev and testing; however when I added your plugin it works perfectly on posts… but not on “Pages”.

    I must have something misconfigured but can’t figure out why the shortcodes aren’t being activated on pages.

    Any ideas?

    Am using WP 3.0.3, php 5

  11. Ignore previous, apparently issue with the theme. I patched the theme with a direct call to do_shortcode and that resolved the issue.

    • Hi Amit,

      If you are using templates to build your pages and are inserting the content directly into the templates then the php shortcode will not work as you can just < ?php //content// ?> into the template, however if you are using the_content() function in the template then it should execute the shortcode properly.

      Thanks
      Jamie

  12. Johnny Mestizo says:

    I am trying to show the value of a custom key for the current post.

    [php]
    $model=get_post_meta($post->ID,”mp2model”,true);
    echo $model;
    [/php]

    in debug it does not error. but when i run it is shows nothing.

    can u help?

    Johnny

  13. Johnny Mestizo says:

    bingo !

    [php]
    global $wp_query;
    $postid = $wp_query->post->ID;
    echo get_post_meta($postid, ‘mp2model’, true);
    [/php]

  14. Hi Hit Reach,

    Thank you for writing this plugin, it is brilliant and is exactly what I was needing :)

    I look forward to future plugin releases you make.

  15. This is FANTASTIC! It solved my problem in 12 seconds flat. THANK YOU!

  16. Yo, this shit is absolutely ridiculous, I had an issue, wordpress seemed to be at its limits, looked up plugins, got yours, PROBLEM SOLVED in less than a minute. Daim – I was blown away from how easy it was to use.

    Keep up the great work, much appreciated it.
    1luv

  17. Jamie,

    I’m also a happy user of your plugin, but for some reason, can’t manage to include a php file. What am I doing wrong:

    [php]
    include (‘http://www.derekbeck.com/form.php’);
    [/php]

    I don’t get my form with the above syntax… what’s wrong?

    Thanks,
    Derek

    • Chris Gilchrist says:

      Hi Derek,

      The syntax is correct. If you let us see what the content of form.php is we’ll look for you :)

      Thanks,
      Chris

      • Well, here’s an example of one I cannot include in this manner:

        [php]
        include (‘http://www.derekbeck.com/1775/social-nowp.php’);
        [/php]

        • Hi Derek

          comparing the code you and Tom(Below)

          you both appear to be including the page with an absolute url (e.g. with the http://www.) however with the latest versions of php, the absolute inclusion has been disabled as standard. this could be why the include is failing; try switching to a relative (e.g. ../../scripts/myscript.php) url for the location.

          Thanks
          Jamie

          • Hi Jamie, thanks for the reply. I was excited to try this, and that fixed it for me. Thanks!

            Is there a way to turn on absolute inclusion, out of curiousity?

            derek

            • Hi Derek,

              You can turn url file-access on by updating the php.ini value: allow_url_fopen from off to on,

              However because allow_url_fopen on creates a security vulnerability for XSS and subsequent updates will turn it back off.
              It is very recommended to not turn on allow_url_fopen and instead use relative links starting with
              $root = realpath($_SERVER["DOCUMENT_ROOT"]); so your include will start: include “$root/inc/include1.php”;

              Thanks
              Jamie

  18. Im having same issue as Derek –

    [php]
    include=(‘http://172.16.1.182/news/preview.php?id=4′);
    [/php]

    Doesnt show up but I can go to the link itself. YOU wont be able to see that though because I am developing it internally –
    Curious as to how to fix. I am using a theme also….

    Thanks –
    Tom

    • BTW this DOES work:
      [php]
      echo “hello world”;
      [/php]

      So I know I am getting the functionality out of it – just missing something on including the DB call

      • Hi Tom,

        comparing the code you and derek (abvve)

        you both appear to be including the page with an absolute url (e.g. with the http://www.) however with the latest versions of php, the absolute inclusion has been disabled as standard. this could be why the include is failing; try switching to a relative (e.g. ../../scripts/myscript.php) url for the location.

        also tom, your syntax is incorrect
        “include=(‘http://172.16.1.182/news/preview.php?id=4′);”
        should be “include(‘http://172.16.1.182/news/preview.php?id=4′);”

        Thanks
        Jamie

        • Yes I saw the = was incorrect hehe –
          Going to try the relative path right now – Although I can get other php commands to work and even tried a different plugin “exec-php’ and can get other php calls to work just not includes.

          Will let you know shortly – thanks for your time! :-)

          • Ok if I put the call in like this –

            [php] include(‘./news/preview.php?id=4′); [/php]

            I get nothing –

            if I call direct

            [php] include(‘./news/preview.php’); [/php]

            without the query string it seems to actually work because it gives me a drop down of which news to select (local or weather) (id 4 is weather) –

            If I go to the http://172.16.1.182/news/preview.php?id=4 in a browser it shows up perfectly….

            Could this be a limitation in my php config – as the wordpress db and the news editing db are completely seperate….

            Thanks again for your time and efforts – I am really frustrated as once I figure out why this doesnt work and can fix it it will open up a HUGE world for us on flexibility

          • Ok Tom,

            When you are including a file you include the src code, so instead of picking up the value in a query string, why not try setting it before the include, for instance..

            $id=4;
            include(‘include’);

            then in the include

            change $id = $_GET['id'];
            to if(!isset($id)){$id = $_GET['id'];}

            Try this and let me know your results :)

            Thanks
            Jamie

          • And you lost me on that one LOL :P I know enough php to be dangerous hehe

            [php]
            $id=4;
            include(‘include’);

            change $id = $_GET['id'];
            to if(!isset($id)){$id = $_GET['id'];}

            include(“/home/rrpi/dev.qmix.local/html/news/preview.php?id=$id”);

            [/php]

            is this even close at all – Sorry – I know we are getting into probably more than standard support and I understand if you cant or dont want to answer beyond the help you have given….

            Thanks for your time thus far –
            Tom

          • Tom,

            I will email you to help explain this rather than fill up this page :)

            Jamie

  19. I am trying to get this to work and it will not. All it does is display my code. I’m not sure what to do.
    [php]
    <?
    // Connect database
    include("connectdb.php");

    // Get all records in all columns from table and put it in $result.
    $result=mysql_query("select * from memberstats");

    /*Split records in $result by table rows and put them in $row.
    Make it looping by while statement. */
    while($row=mysql_fetch_assoc($result)){

    // Output
    echo "id : $row[id] “;
    echo “FirstName : $row[FirstName] “;
    echo “LastName : $row[LastName] “;
    echo “GoalWeight : $row[GoalWeight] “;

    // Add a link with a parameter(id) and it’s value.
    echo ‘Update‘;

    }

    mysql_close();
    ?>
    [/php]

    Any help would be appreciated. Thank you.

    • Hi Andrew,

      My first note would be the use of < ? and ?>, they are not needed as that is what the [php] [/php] handle.

      Try removing the php open and close and try again and let me know the results :)

      Thanks
      Jamie

  20. What an awesome plugin! Thanks so much for developing this, and for all the support you offer for it here too. It’s really appreciated!

    I have a question though, I started off modeling your code samples, and whenever I used global there was no output, when I removed the global scope on variables it worked fine. Would this be due to a server setting, or what?

    Thanks!
    Donna

    • Hi Donna,

      Thank you for your comment, it is always nice to hear your work being appreciated :)

      The examples provided are purely just examples, the global scope is not always necessary, i just provided it in the example. if you ever get a case of there being no output when you think their should be, just use the debug tag to see what code is actually running :)

      Thanks
      Jamie

      • Thanks for your reply Jamie! I did use the debug tag (great feature!), and the code was fine, it just wasn’t outputting anything, as soon as I removed the ‘global’ it worked just as expected. So I was just wondering what might have caused it.

        Thanks again!

  21. Mental Workout says:

    do the variables carry from one [php]…[/php] block to another on the same page?

    for example, will this work as i cant get it to work on the same page?

    [php] $var = 3; [/php]

    [php] echo $var; [/php]

    when i try, the second set returns nothing

    cheers

    serge

    • Chris Gilchrist says:

      To get it to carry from one block to another you need to set the variable up as global. Then in each block you need to make a reference to the global objects IE global $var; at the start

      • mental workout says:

        brilliant … it works now :-)

        cheers and thanks

        serge

        • Chris Gilchrist says:

          You’re welcome :)

          If you benefited from this plugin and appreciate our support, both of which are free, please link to our site to help spread the word so this plugin can help as many people as possible.

  22. Hey Chris,

    plugin in version 1.2.3 works fine for me. Excellent work.
    You can have a look here if you like:

    http://www.rustystrings.eu/?page_id=1434

    Cheers – have a couple of beers.

    • Chris Gilchrist says:

      Hi, glad it helped! If you have space please add a link to us in your blogroll to help other people find the plugin :)

  23. Chris Luckett says:

    I’m creating a new WordPress site from an old website. The page I’m trying to create (a Weather page with a changing forecast) needs a php page. I was told the following: “To display the output of the application, this needs to be pasted into a WordPress template:”

    <? php include(“/path/to/ec-forecast.php”); ?>

    (replace /path/to with the actual path to the file.)

    I pasted this code,as is, into my html part of the page editor above the forecast text and graphics code (which are showing up fine on the page). I have put the ec-forecast.php file and the ec-forecast-en.txt file into my theme’s Includes folder.
    After installing the ‘Allow PHP in Posts and Pages’ plugin, and adding the [php] and [/php] before and after the above code,I checked the page, but nothing seemed to have changed.

    What am I doing wrong?

    P.S. I’m a total newbie at this.

    • Hi Chris

      When using includes, you will need to do absolute includes, e.g. < ?php include("http://path/to/ec-forcast.php");?> or for our plugin it will be [php]include(“http://path/to/ec-forcast.php”);[/php]

      I hope this helps

      Thanks
      Jamie

  24. Just wanted to say thanks for an awesome plugin. Adding just a little PHP on a page (such as I did with the IP address on my contact page) can make such a difference.

    Had a slight problem at first until I read the comments here and noticed the syntax of adding a \ before any [].

  25. Hy Jamie

    Using your plugin and trying to make a dropdown menu with elements from a array.
    Here is how my code looks like:

    [php]
    include ‘config.php’;
    include ‘opendb.php’;
    $comanda = ‘SELECT name FROM user ORDER BY id DESC’;
    $result = mysql_query($comanda);

    while($row = mysql_fetch_array($result))
    {
    echo $row\['nume'\];
    echo “[br /]“;
    }
    $row = mysql_fetch_array($result);

    echo ”;
    echo ‘Choose client:‘;
    echo ”;

    foreach ($row as $value)
    {
    echo ” . $value . ”;
    }

    echo ‘Client name: ‘ . $value . ‘[br /]Telephone: ‘;
    echo ‘
    ‘;
    echo ”;

    Table OK; Dropdown appears but is empty. No values inside.

    I’ve also tryed:

    foreach ($row as $value)
    {
    echo ‘\[option\]‘ . $value . ‘\[/option\]‘;
    }

    but no results.
    So, if you could help me a little bit, I would be appreciate.
    Thank you!

    P.S. Forget to mention that the foreach ()… outside the table works fine. So it has to be somthing with the way I echoed the table and its elements.
    Tryed diferent methods [] and no luck.

    P.P.S. Code got stripped really bad:

    Here is the part with problems:

    echo ‘\’;
    foreach ($row as $value)
    {
    echo ‘\‘ . $value . ‘\‘;
    }
    echo ‘\’;

    echo select;
    foreach
    {
    echo option $value /option;
    }
    echo /select;

    • Hi Lucian,

      I have a couple of things to note here,

      For your includes, you should stick to absolute paths rather than relative paths as this is disabled in later versions of PHP.
      When you echo the “ …. ” these brackets need to be square ones or they will be removed.

      Try it again with these changes and let me know the results :)

      Thanks
      Jamie

  26. Hi
    I am having a challenge with using php on a page to display results from a subscription database. The pages I am working on are:

    caribbeanluxuryyachtcharters.com/luxury-yachts/motor-yachts-2/
    caribbeanluxuryyachtcharters.com/luxury-yachts/catamarans/

    I created a results.php template page with the followin php coding:

    <?php
    echo "”;

    $instr = $_SERVER['QUERY_STRING'];
    if(!$_REQUEST['ebclick']){

    $ch = curl_init();
    $timeout = 5; // set to zero for no timeout
    if($_REQUEST["yidi"]==1){
    $instr=$_SESSION["mystr"];
    }else{
    if($_GET["subin"]){

    $instr=”user=265″;
    if($_REQUEST["boattype"])
    $instr.=”&boattype=”.$_REQUEST["boattype"];

    if($_REQUEST["guests"])
    $instr.=”&guests=”.$_REQUEST["guests"];

    if($_REQUEST["ylocations"]){
    $instr.=”&ylocations=”.$_REQUEST["ylocations"];
    }else{
    $instr.=”&src3=1&src5=1&src7=1&src8=1″;
    }
    if($_REQUEST["startmonth"])
    $instr.=”&startmonth=”.$_REQUEST["startmonth"];

    if($_REQUEST["startday"])
    $instr.=”&startday=”.$_REQUEST["startday"];

    if($_REQUEST["startyear"])
    $instr.=”&startyear=”.$_REQUEST["startyear"];

    if($_REQUEST["endmonth"])
    $instr.=”&endmonth=”.$_REQUEST["endmonth"];

    if($_REQUEST["endday"])
    $instr.=”&endday=”.$_REQUEST["endday"];

    if($_REQUEST["endyear"])
    $instr.=”&endyear=”.$_REQUEST["endyear"];

    if($_REQUEST["pricefrom"])
    $instr.=”&ylocations=”.$_REQUEST["pricefrom"];

    if($_REQUEST["scubadet"])
    $instr.=”&scubadet=”.$_REQUEST["scubadet"];

    $_SESSION["mystr"]=$instr;

    }else{
    $instr=”user=265&boattype=X&guests=900″;

    }

    }

    curl_setopt ($ch, CURLOPT_URL, “http://www.centralyachtagent.com/snapins/snyachts-xml.php?”.$instr);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $xml = curl_exec($ch);
    curl_close($ch);

    include ‘xml_regex.php’;
    $news_items = element_set(‘yacht’, $xml);

    foreach( (array)$news_items as $item) {
    $yid = value_in(‘yachtId’, $item);
    $size = value_in(‘size’, $item);
    $yn = value_in(‘yachtName’, $item);
    $ypax = value_in(‘yachtPax’, $item);
    $ycabins = value_in(‘yachtCabins’, $item);
    $ytype = value_in(‘yachtType’, $item);
    $lowprice = value_in(‘yachtLowPrice’, $item);
    $highprice = value_in(‘yachtHighPrice’, $item);
    $yebpic = value_in(‘yachtEbrochurePic’, $item);

    $item_array[] = array(
    ‘yid’ => $yid,
    ‘size’ => $size,
    ‘yachtname’ => $yn,
    ‘pax’ => $ypax,
    ‘cabins’ => $ycabins,
    ‘type’ => $ytype,
    ‘lowprice’ => $lowprice,
    ‘highprice’ => $highprice,
    ‘ebrochurepic’ => $yebpic
    );
    }

    if (sizeof($item_array) > 0) {
    $count = 0;
    echo “Yacht Search“;
    echo “”;
    $cnt=$mbg=0;
    foreach ($item_array as $item) {
    $cnt++;$mbg++;

    if($cnt==1)
    echo “”;
    $bg=””;
    if($mbg % 2)
    $bg=”bgcolor=’#E4E4E4′”;
    echo “”;
    echo “”;
    //
    echo ““.$item["yachtname"].”“;
    echo “”.$item["type"].”   “.$item["size"].””;
    echo “”;
    echo “Guests: “.$item["pax"].”  Cabins: “.$item["cabins"].””;
    echo “Low Price: “.$item["lowprice"].”High Price: “.$item["highprice"].””;
    echo “View Ebrochure“;
    echo “”;
    echo “”;

    if($cnt==4){
    $cnt=0;
    echo “”;
    } //cnt =3
    } //for loop
    if($cnt<4){
    for($cl=$cnt;$cl<4;$cl++)
    echo " “;
    echo “”;
    }
    echo “”;
    } // sizeof
    } // not ebclick

    if($_REQUEST['ebclick']){
    $yid=$_REQUEST["yid"];
    $ynm=$_REQUEST["ynm"];
    $user=265;
    $act=”results.php”;
    $instr=”user=265&idin=”.$yid.”&act=”.$act;

    $ch = curl_init();
    $timeout = 5; // set to zero for no timeout
    curl_setopt ($ch, CURLOPT_URL, “http://www.centralyachtagent.com/snapins/ebrochure-xml.php?”.$instr);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $xml2= curl_exec($ch);
    curl_close($ch);
    //echo $xml2;

    // display file

    //include ‘xml_regex.php’;
    //$news_items = element_set(‘yacht’, $xml);
    // print_r($news_items);
    // foreach($news_items as $item) { // will only be once
    //$yid = value_in(‘yachtId’, $item);
    //call template
    // include “templ.php”;
    // echo $item;

    //}

    /*
    $file = “data.xml”;
    $xml_parser = xml_parser_create();

    if (!($fp = fopen($file, “r”))) {
    die(“could not open XML input”);
    }

    $data = fread($fp, filesize($file));

    fclose($fp);
    */
    $data=$xml2;
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $data, $vals, $index);
    xml_parser_free($xml_parser);

    $params = array();
    $level = array();
    foreach ($vals as $xml_elem) {

    if ($xml_elem['type'] == ‘open’) {
    if (array_key_exists(‘attributes’,$xml_elem)) {
    list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
    } else {
    $level[$xml_elem['level']] = $xml_elem['tag'];

    }

    }
    if ($xml_elem['type'] == ‘complete’) {
    $start_level = 1;
    $php_stmt = ‘$params’;
    while($start_level < $xml_elem['level']) {
    $php_stmt .= '[$level['.$start_level.']]';
    $start_level++;

    }
    $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
    //echo $php_stmt."”;
    eval($php_stmt);
    //echo eval($php_stmt);

    }
    }
    //echo $params['YACHTS']['YACHT']['YACHTHIGHPRICE'].””;

    //echo “”;
    //print_r ($params);
    //echo “”;
    include “templ.php”;
    //include “pics.php”;

    }
    echo “”;
    ?>

    Your input would be appreciated.
    Chris

    • Hi Chris,

      Unfortunately this section is only for support on using the Word Press plugin “Allow PHP in Posts and Pages”.

      As the request is for support on a PHP template file we cannot assist here, however you can contact us for more information and assistance on this matter.

      Thanks
      Jamie

  27. Number Phi says:

    Hi!
    Can I use SOAPClass objects in PHP code with this plugin? If so, how?
    Thanks

  28. Thank you for the great plugin, but unfortunately I just discovered today that my RSS went kaput once I installed Allow PHP In Posts And Pages. I tried turning all plugins one by one until I saw that turning yours off gets the RSS back in order.

    Curiously that only happens with the theme I’m using – I tried switching to a twentyten and the issue also went away (mind you I’m using Atahualpa which is a very common theme so there are going to be a few folks out there that are not even aware their RSS disappeared on them)

    • Hi Ivan,

      Thank you for your comment, because the plugin doesn’t change anything in relation to the rss feed as it is just a parsed shortcode, it could be that there is a problem with the themes RSS file that cannot handle the shortcode, in which case this is an issue for the theme’s creator.

      Thanks
      Jamie

  29. Hi – very useful plugin – thanks. I’m having problems using “heredoc”. For example:
    [php] echo <<<EOF
    Some random stuff
    EOF
    [/php]

    Gives an unexpected T_SL error on line 2. So does:

    [php]echo <<<EOF
    standard things
    EOF[/php]

    I've got a page with a lot of different variables to interpolate. Since each [php][/php] acts like a discrete scope, I can't set the variables in one and then pick them up in another without globalising them. But a long heredoc with a pre-ample that sets up the variables, is perfect. Except that it doesn't work… Importing variables without making them global is quite a challenge (I don't want persistence beyond the current page).

    • Hi Jeremy,

      you could try using sessions instead for a better result, also, you need to include the semi-colon at the end even if its the final line.

      Thanks
      Jamie

      • Thanks Jamie. I have also tried:
        [php]echo <<<EOT
        Testing
        EOT;[/php]

        and:

        [php]
        echo <<<EOD
        Experimenting
        EOD;
        [/php]

        The T_SL error appears to be triggered on seeing the "<<<HERE" part. It fails long before seeing the terminal semicolon (or not).

        Using session storage gets me back into storing page-specific data over multiple pages. Or, I suppose I could write something that cleaned the page-specific data out of $_SESSION at the end of the page. Clumsy, but it'd probably work.

        Think about forms, and when it is right to persist data. I don't want to persist private information over the boundary of completing a validated form. So uncleared sessions potentially leak information to later pages or are potentially snoopable by someone coming past a browser that hasn't been properly closed down. I'd rather use something like a scope that is available for the current page only (no such concept seems to exist in PHP).

        • Hi Jeremy,

          For the heredoc part, just place the string in to quotes, the wysiwyg editor doesnt currently support this heredoc to well because of the syntax.

          Thanks
          Jamie

  30. Wolfgang Preiss says:

    if I use echo in the php script, obviously the wordpress css isn’t used. It uses a different font, and the lines are too long for my theme.

    You can check this here:
    http://blog.piraten-streaming.de/?page_id=603&preview=true&id=143

    Is there a work around?

  31. I’m trying to use this script –
    http://www.anyexample.com/programming/php/php_mysql_example__display_table_as_html.xml

    it displays a couple of rows nicely then the rest looks like its in one cell

    • Hi Salini,

      This appears to be a coding issue on your end, not with the plugin its self, also without a link we can be no further assistance to you on this matter.

      Thank,
      Jamie

  32. I’ve tried using this code to add the current date to a side widget but nothing comes up but the actual code….I have installed your plugin….Any suggestions?

    • Hi Belinda,

      Most themes as a default do not process shortcodes in the sidebar, however you can change this by adding the following to your theme’s function.php file (if possible)
      add_filter('widget_text', 'do_shortcode');

      Future versions of allow PHP automatically add this in.

      Thanks
      Jamie

  33. Hi,

    I installed the plugin and found out that this plugin doesn`t work on Pages.

    How can i make it work?
    using wordpress v3.2

    Thanks

  34. Hi,

    Just updated to the latest version and now I get this error:-

    Parse error: syntax error, unexpected ‘<' in C:\xampp\htdocs\savc\pw\wp-content\plugins\allow-php-in-posts-and-pages\allowphp.php(49) : eval()'d code on line 1

    This is using your sample code …

    Help please!

    Phil.

  35. What is the correct format for inserting snippets into posts?

    I made a snippet named: EN
    with code: echo Date(“F Y”);

    I tried calling it with [php]EN[/php] and doesn’t work.

  36. Hi Jamie
    I get the message below when I run this snippet (id=1)

    $username= $_GET(“username”);
    echo $username;

    ==============================
    Fatal error: Function name must be a string in /home/sites/…../wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(50) : eval()’d code on line 1
    ================================
    The page that I run it from contains only this:
    [php function=1 debug=1]
    [/php]

    It has a query string that I’m trying to access.

    No problem when the snippet is
    echo “hello world”;

    Can you help please?

    • Hi Nick,

      Its [ ] brackets for $_GET and not ( ) brackets as $_GET is not a function :)

      Thanks
      Jamie

      • Thanks Jamie – I should have noticed that but my php is very rusty.
        And also thanks for this great plugin – it is just what I was looking for to do some simple coding. I’ll try not to bother you with silly problems in the future :O)

        • Hi Nick,

          It’s good to see our work appreciated :)

          Please do share our plugin via social media sites or even make a donation towords the cost of maintaining the plugin.

          This will be greatly appreciated.

          Thanks
          Jamie

  37. Hi Jamie,

    Would you mind checking this line of code?

    if ($_POST['CO']==’imie’) {

    Looks like it still does not support Post method. Can you advice on what to do?

    The code we are writing works with PHP Custom Wiget plugin, but we need it in pages :) So we need your plugin to work.

    Thank you for any help.
    Peter

    • Hi Peter,

      All square brackets ( [ and ] ) need to be escaped otherwise they get turned into < and > (respectively) at run time,

      Either: use the snippets for your php code, or escape the [ ] using backslashes: \[ and \]

      Thanks
      Jamie

  38. Great, news. Yep that helps a lot :)
    Thank you for great plugin and for quick response.

    Cheers,
    Peter

    • Chris Gilchrist says:

      Hi Peter, please take 2 mins to help support the plugin and use any of the promotion suggestions on the plugins admin page. Thx :)

  39. Nick Waites says:

    Hi Jamie
    When I create a snippet containing the tag, the closing tag always disappears, eg
    ?>
    hello
    Any html following therefore gets screwed up.
    It’s not a problem if I put the code directly into a page using your [php]…[/php] short codes, only when I create a snippet in the plugin page.
    Is there something I’m doing wrong?
    Nick

  40. Nick Waites says:

    Hi Jamie
    Sorry, didn’t realise that html tags get stripped out of comments. My previous comment should read

    When I create a snippet containing the textarea tag, the closing tag, /textarea, always disappears, eg
    ?>
    <textarea cols=”30″ rows=”5″> hello < /textarea >

    • Hi Nick,

      when you are doing a snippet with html at the end and not php, you will need to re-open the php tag, so at the end of:

      ?>
      <textarea cols=”30″ rows=”5″> hello < /textarea >

      add in the <?php again, this should stop the closing tag from disappearing.

      Thanks
      Jamie

      • Nick Waites says:

        Thanks for the reply Jamie.
        I tried your suggestion but the /textarea tag still disappears. I’ve experimented with several other tags which all work OK. It just seems to be this particular tag that causes problems.

        • Hi Nick,

          This is strange, i will look into the issue and let you know what we find, for the minute, if you replace the < with &lt; and the > with &gt; it will stop it being removed,

          Thanks
          Jamie

  41. Best php code in post and pages.
    Thanx for the plugin :)
    It Rocks…

    Mvg,
    Avinash Bhageloe

    • Hi Avinash

      Thank you for your comment, its good to see work appreciated :)

      Please take 2 mins to help support the plugin and use any of the promotion suggestions on the plugins admin page

      Thanks :)
      Jamie

  42. i am having a problem to execute a simple query to get and count the number of posts.
    here is my code

    [php]
    mysql_pconnect(“localhost”,”root”,”123″);
    mysql_select_db(“mydb”);
    $query_cat_post = mysql_query(“SELECT * FROM nc_posts”);
    $num_cat_post = mysql_num_rows($query_cat_post);
    echo $num_cat_post;
    [/php]

    when i run the page i am getting this error.

    Parse error: parse error in C:\wamp\www\wordpress\wp-content\plugins\allow-php-in-posts-and-pages\allowphp.php(50) : eval()’d code on line 4

    what’s wrong? how to excute my custom queries? please help. Thanks in Advance

  43. When I go to upload more information to the website there is a box that I can not remove off the screen it tells me I need to update to WordPress 3.2.1 I was told I need to back up all my information (that has been down loaded to the website) on to the computer not just a flash drive or disk. How would I backup my information and download the the new WordPress?

    • Chris Gilchrist says:

      You will find help on general wordpress related issues on their website. Please only use this channel for plugin support.

  44. This php plugin is pretty useful, but it lacks one very important thing: Parameters. I have a download site where I was hoping to use this plugin to deliver hashes for the files, but as it is now I cannot do that. Instead of having to reinvent the wheel over and over for each file it would be much better either if there was a way for the snippets to accept parameter input, or if you could provide some basic hash tags such as [md5][/md5], [sha1][/sha1] or maybe even [hash=sha512][/hash] to make this simplier. I’m definitly willing to donate some money if this could be acomplished.

  45. Hi Johan,

    You can already use MD5 and SHA1 functions within PHP by calling md5() or sha1() with a string parameter.

    Thanks
    Jamie

  46. Hi, I am getting:

    Parse error: syntax error, unexpected ‘>’

    when trying to run anything that ‘echos’ a variable. Such :
    [ php ]
    $a_var = “a string”;
    echo $a_var;
    [ /php ]

    • Hi Nick,

      What version of the plugin are you using?

      I have just tested it and cannot recreate the issue on the latest version using the code supplied.

      Thanks,
      Jamie

      • Version 2.1.0

        • Have you tried using the debug=1 attribute?

          • Parse error: syntax error, unexpected ‘>’ in /wp/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(50) : eval()’d code on line 3

            Notice: Undefined variable: res in /wp/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php on line 52

            $avar = “test”;
            echo “$a
            var”;

            Seems like it is replacing stuff that it should be leaving alone.

            • Hi Nick

              Can you check the html view for the code and check that there are no additional html tags in your code, i can re-create the error if i use :

              [php]
              $a_<em>var = “a string”;
              echo $a_var;
              [/php]

              in the html view, but it appears as

              [ php]
              $a_var = “a string”;
              echo $a_var;
              [/php ]

              in visual mode

  47. Nope. I had visual mode disabled.

    It was the ‘markdown’ plugin that was doing it. Disabling that fixed it.

    Thanks for the help.

  48. Hello, can anyone tell me whats wrong?

    $query = “SELECT `firstname`,`lastname`,`default_picture`,`description`,DATE_FORMAT(NOW(), \”%Y\”) \”-\” DATE_FORMAT(`birthday`, \”%Y\”) \”-\” (DATE_FORMAT(NOW(), \”00-%m-%d\”) < DATE_FORMAT(`birthday`, \"00-%m-%d\")) AS age,DATE_FORMAT(`birthday`, \"%D %M %Y\") as verjaardag FROM `jos_joomleague_players` WHERE `checked_out`=0 ORDER BY `lastname` DESC";
    $result_handle = mysql_query($query) or die("Query failed");

    I think it's somewhere in this:
    DATE_FORMAT(NOW(), \"%Y\") \"-\" DATE_FORMAT(`birthday`, \"%Y\") \"-\" (DATE_FORMAT(NOW(), \"00-%m-%d\") < DATE_FORMAT(`birthday`, \"00-%m-%d\")) AS age

    Cause when i remove it from the query and i only show this:

    $query = "SELECT `firstname`,`lastname`,`default_picture`,`description`,DATE_FORMAT(`birthday`, \"%D %M %Y\") as verjaardag FROM `jos_joomleague_players` WHERE `checked_out`=0 ORDER BY `lastname` DESC";
    $result_handle = mysql_query($query) or die("Query failed");

    it does work…

    please help..
    thnx!!

  49. This plugin appears to be breaking the WYSIWYG editor. Is this a known issue or a ‘feature’? https://skitch.com/shalacoonline/f7e3x/edit-page-sycle-localhost-wordpress

    • Chris Gilchrist says:

      With over 12,000 users it’s unlikely to be this plugin causing your problems :)

      • Thank you for your prompt and thoughtful response.

        I deactivated all additional plugins to confirm that there was not another plugin acting as a silent accomplice. Additionally I disabled my functions file to reduce any additional noise.

        Results were the same. When “Allow PHP in Posts and Pages” is activated WYSIWYG editor breaks. Deactivated plugin works.

        I am running wordpress-3.2.1 using a custom child theme w/ parent twenty eleven.

        Have you tested plugin w/ latest WP on 2011 theme?

        Detailed desctiption of “WYSIWYG editor breaks:
        Screenie: https://img.skitch.com/20111002-ehqxqtby1k11qn3n5gqhs5hgq8.png

        mceToolbar flashes for a second and then disappears. Toggling between html and back to the visual editor with an empty posts first generates:

        second:

        third:

        • Hi guys,

          There has been an update released, it would appear that it could be broken my faulty set-ups in blogs that are in a sub folder of a site,

          This issue has been addressed and an update has been released (2.1.05) although, with all the users, I am surprised that no one else has had a problem if this is the case :)

          Thanks,
          Jamie

      • BROKEN EDITOR – I can confirm…

        The plugin breaks the WYSIWYG editor – at least on my site – when :

        - WordPress is installed in a subdirectory
        - A .htaccess file rewrites the URL to the root.

        The plugin should ignore the rewriting rule, but it’s not the case. Therefore, it cannot open correctly the AP.js and throws an error that breaks the editor.

        Example :

        The true URL of the AP.js file (if WordPress is installed in a subdirectory) :
        http://www.site.com/wordpress/wp-content/plugins/allow-php-in-posts-and-pages/AP.js

        The rewritten URL. The plugin tries to open the JS file at this address and, obviously, generates an error
        http://www.yoursite.com/wp-content/plugins/allow-php-in-posts-and-pages/AP.js

        If you deactivate the plugin, the editor is not broken anymore.

        • problem is caused because of an absolute defined path in “/plugins/allow-php-in-posts-and-pages/allowphp.php” file. change line 488

          define( “APIP_PLUGIN_URL”, get_bloginfo(‘wpurl’).”/wp-content/plugins/” . APIP_PLUGIN_DIR );

          to

          define( “APIP_PLUGIN_URL”, WP_CONTENT_URL . “/plugins/” . APIP_PLUGIN_DIR );

          problem will be solved. plugin should not assume that the default folder is “wp-content”. an update would be useful.

  50. Hello,

    I uninstalled the plugin. However, I saw that there was still a table left in the DB called “wp_allowPHP_functions”. Can I just delete this table too?
    How to make a clean uninstall?

    Thanks.

    • Hi Alex,

      A clean uninstall is not currently a feature of the plugin, however it is something that has been listed for the next update.

      For the minute however, deleting the table and option for the plugin is all that is necessary

      Thanks,
      Jamie

  51. I want to show the most recent post on a page with its title as the permalink. This is the code I’m trying to use:

    query_posts(‘showposts=1′);

    while (have_posts()): the_post();
    echo ‘[a href="';
    the_permalink();
    echo '"]‘;
    the_title();
    echo ‘[/a]‘;

    endwhile;

    The above code results in the following:

    Parse error: syntax error, unexpected ‘[‘, expecting ‘,’ or ‘;’ in /home/****/public_html/testing/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(50) : eval()’d code on line 4

    However, when I use the following code:

    query_posts(‘showposts=1′);
    while (have_posts()): the_post();
    the_permalink();
    the_title();
    endwhile;

    everything shows up, but the title and permalink are just next to each other. What markup should I use?

    • Hi Ken,

      The issue is with your quotation marks, you have used improper single quotation marks.

      the correct way to form the statement is with single quotation marks and not back or forward ticks

      [php]query_posts(‘showposts=1′);

      while (have_posts()): the_post();

      echo ‘[a href="';
      the_permalink();
      echo '"]‘;
      the_title();
      echo ‘[/a]‘;

      endwhile;

      [/php]

  52. Hi charlie can you please tell me what am I doing wrong in the snippet below ?

    [php]
    if ($wt_movie_enable == “false”) { }

    else { [/php]
    echo “[object id="player" width="620" height="360" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"][param name="movie" value="http://www.videobb.com/e/rjsx68m"][/param][param name="allowFullScreen" value="true" ][/param][param name="allowscriptaccess" value="always"][/param][embed src="http://www.videobb.com/e/rjsx68m" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="620" height="360"][embed][/object]“;

    [php] } [/php]

    Thanks for making this plugin

  53. oops sorry that was a wrong snippet please disregard it heres the one I am using and it does not work

    [php]
    if ($wt_movie_enable == “false”) { }
    else {
    echo “[object id="player" width="620" height="360" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"][param name="movie" value="http://www.videobb.com/e/rjsx68m"][/param][param name="allowFullScreen" value="true" ][/param][param name="allowscriptaccess" value="always"][/param][embed src="http://www.videobb.com/e/rjsx68m" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="620" height="360"][embed][/object]“;
    } [/php]

    • Hi Julian,

      It could be the use of the quotation marks, try inverting them, so that the entire object code is wrapped in single quotes instead of double quotes as it will be causing a parsing issue with the double quotes inside of the object tag

      Thanks,
      Jamie

  54. I’m getting a parse error for this code placed into a page:
    [php]
    $GLOBALS['code']->printCatalog();
    [/php]

    The error:
    PHP Parse error: syntax error, unexpected ‘>’ in /usr/home/users/asamplesite/public_html/wp-conten
    t/plugins/allow-php-in-posts-and-pages/allowphp.php(50) : eval()’d code on line 2

    I’ve tried escaping various things but to no avail.

    • Hi Matt,

      Please remember that all square brackets ( [ and ] ) are swapped to the counterparts at runtime, and all are removed, so for the time being, you will need to write your code as $GLOBALS\['code'\]-]printCatalog();

      We are working on an improved tag replacement system however.

      Thanks,
      Jamie

  55. I very much like the way this plugin works.

    Currently,using WP3.2.1, when I’m in debug mode, I see the following error:

    Notice: Undefined variable: res in /home/mysite/www/www/wordpress/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php on line 52

    what do I need to do to get past that?
    Thanks

    • Hi Clairence,

      The notice is caused by a mis-declared variable and doesn’t effect the workings of the Plugin, this notice has been rectified in the latest version due for release in the very near future :)

      Thanks,
      Jamie

  56. Hi, could you help me with this code.

    This is the php code which is working fine in my header.php file:

    $exl_posts,
    ‘paged’ => $paged,
    )
    ); ?>

    <div id=”post_”>

    <a href="” class=”thumb”> trim(strip_tags( $post->post_title )),
    ‘title’ => trim(strip_tags( $post->post_title )),
    )); ?>

    <a href="”>

    I have tried to get it to work in a page but I am getting a number of error messages back.

    this is the attempt I had made:

    [php] query_posts(array(‘post__not_in’ => $exl_posts,’paged’ => $paged,));

    if ( have_posts() ) : query_posts(‘category_name=news&posts_per_page=10′);

    echo ‘[div id="loophome"][/div]‘;

    while ( have_posts() ) : the_post();

    [/php]

    ‘[div [php] post_class(‘post’); [/php] id=”post_[php] the_ID(); [/php]“]’

    [php] if ( has_post_thumbnail() ) :[/php]
    ‘[a href="'[php] the_permalink() [/php]“][php] the_post_thumbnail(‘thumbnail’, array(
    ‘alt’ => trim(strip_tags( $post->post_title )),
    ‘title’ => trim(strip_tags( $post->post_title )),
    )); [/php][/a]
    [php] endif; [/php]

    [div]
    [span][php] the_time(__(‘l, jS F Y’)) [/php][/span]
    [/div]
    [h2][a href="[php] the_permalink() [/php]“][php] the_title(); [/php][/a][/h2]

    [div][php] if (function_exists(‘smart_excerpt’)) smart_excerpt(get_the_excerpt(), 55); [/php][/div]
    [/div]

    [php] endwhile; [/php]

    [/div]

    [php] endif;

    wp_reset_query();

    [/php]

    All help greatly appreciated, thank you.

    • Hi Liam,

      The issue could be surrounding the use of the [/php] mid function, try swapping the ones inside the function to the proper PHP closing tag ( ?> ), or even consider turning it into a Snippet, then using that instead of writing it into the post.

      Thanks,
      Jamie

  57. Great plugin! Just installed latest version, on WP 3.1
    Trying it out with putting in default values in forms; works fine with TEXTAREA, but INPUT doesn’t seem to work. Does the code not work within tags?

    • Hi Owen,

      I just tested it with: <input type=’text’ value=’[php debug=0] echo “hello World”;[/php]‘ /> and it all worked okay.

      could it be an issue with the variable you are trying to echo?, e.g. is it empty?

      Thanks,
      Jamie

  58. I was using double quotes inside the tag for the values; I took out the double quotes for the value I was trying to modify via and php call and it worked. For future attempts I’ll remember the single quotes option. Ta!

  59. Hi Jamie,

    for some reason ist not possible to add a hyperlink!?
    echo “[a href=\"".$row['url'].”\” target=blank]» “.$row['url'].”[/a]“;

    brings out this [a href="http://www1.link.de" target=blank]» http://www1.link.de and the transformed right…hmmm what is worng with my echo??? or me ? ;-)

    • Hi Jörg,

      It appears that the match doesn’t like the $row section; try breaking it into several echos instead, so something similar to:

      echo "&lt;a href='";
      echo $row['url'];
      echo "' target=blank>» ";
      echo $row['url'];
      echo "[/a]"; [/php]

      The problem is, there are so many possible ways to do something, its hard to match them all, or even to think of them all, it will be added to the list for a solution.

      an alternative solution is to escape the square brackets that are meant to be there, then use [php mode=old] to use the older version of the code replace.

      Thanks,
      Jamie

  60. Not sure I am getting this correct This displays nothing should be simple

    echo “”;

  61. Hi,

    I can not get the function of this:

    ” if ($lan “_”) $query=”SELECT * FROM dbcamp WHERE Status=’1′ AND Lan=’” . $lan . “‘ ORD…….. ”

    The outout will be like this:

    ” if ($lan “_”) $query=”SELECT * FROM dbcamp WHERE Status=’1′ AND Lan=’” . $lan . “‘ ORD………”

    Do you have a syntax for this so i can get correct output.

    Thank you, Peter.

    • Hi Peter,

      Has there been parts of your comment removed? as the code you have commented in generally invalid.

      Thanks
      Jamie

    • Yes, some of my are removed. I found the solution for tis. Next
      problem i have is this:

      Output: [a href=http://www.letacamping.se/?page_id=10&Id=871]Kustcamp
      Gamleby // Hammarsbadet

      Code:
      echo “[TR]“;
      echo “[TD]“;
      echo “[a href=http://www.letacamping.se/?page_id=10&Id=$id]“;
      echo “$camping[/a]“;
      echo “[/TD]“;
      echo “[TD]$ort[/TD][TD]$telefon[/TD][TD]$lan[/TD]“;

      I want to change the [ and ] to in the output.

      You can see the output at http://www.letacamping.se/?page_id=8 after
      you have pou on the sök “button”

      Thank you for your support.

      /Peter

  62. Hi Jamie,

    I am trying to use your plugin on Pages and Widgets with mixed success.
    On one page I have code in the Page and 2 widgets.
    While one Widget works fine, the second stops further normal widgets from rendering. It doesn’t matter which order the Widgets are in… the second one stops the others (so it’s not the code that’s doing it). The only way around this is to put the second one at the bottom! I’m no expert so maybe you can help?

    Thanks

  63. Chris Gilchrist says:

    Hi John,

    If you can’t find the problem please send the link to your page so we can look or it could take a while to guess what’s wrong :)

    Thanks,
    Chris

  64. hi

    i m using following code

    [php]
    $args = array( ‘numberposts’ => 2,’category’ => 16);
    $postslist = get_posts( $args );
    foreach ($postslist as $post) : setup_postdata($post);

    [tr]
    [td][h1]echo substr( strip_tags( get_the_title() ),0,35);[/h1] [br] [/br] [span class="small_date"]echo the_time(‘j M’);[/span][/td]
    [/tr]
    [tr]
    [td]echo substr( strip_tags( get_the_excerpt() ),0,35);[br][/br] Read More[/td]
    [/tr]
    endforeach;
    [/php]

    and i m getting following error

    Parse error: syntax error, unexpected ‘<' in /home/content/89/8431289/html/kaveri/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(77) : eval()'d code on line 5

  65. thanks,

    Jamie for reply

    but i m using same code when i only use

    [php]

    $args = array(’category’ => 16);

    echo ‘something’;
    [/php]

    it was ok, but when i use

    [php]

    $args = array( ‘numberposts’ => 2,’category’ => 16);

    echo ‘something’;

    [/php]

    it gives the same error as i mention earlier post also in code i have converted
    every tags to [][/]

    thanks once again for the help………….

  66. Hello Jamie,

    I updated to the beta version this afternoon.

    I am experiencing a weird bug where [form ... and [img ... are not swapping as expected, the rest of my tags are, [/form] seems to convert fine.

    Have you any ideas why this is happening?

    Thanks in advance,

    Scott

    • Hi Scott,

      the plugin is currently in beta testing for a better tag method, the most recent one isnt as effective as first thought and will be reworked, in the mean time, you can enable the older version in the plugin options that requires all < and > to be converted into [ and ] respectively, and all [ and ] to be escaped using a back slash.

      an alternative method is to use the code snippets in the options page, where no tags need to be swapped out.

      Thanks,
      Jamie

      Thanks,
      Jamie

  67. Hi Jamie! And thank you for your work.

    I have a problem: if I define a variable for instance in a page, that variable is not available in another [php][/php] part (like a widget)

    And also the variables set in the theme script aren’t working:

    In the wp-content/themes/theme/header.php file I have a
    require(‘config.php’);

    this config.php contains a lot of very important variables and functions I use in my site.

    then, the code of all my wordpress pages is something like:

    [php]
    $page_id=”xyz”;
    include(‘./pages/pages.php’);
    [/php]

    If I use a require_once(config.php) in that pages.php, the file is not included. I can’t include it again because it’s a huge waste of resources (and it contains functions, which I cannot redeclare)

    Do you know how can I make those variables to be “global” without manually edit all of them?
    I can edit any server configuration if needed…

  68. nvm for my last post. I’ll set all the variables as global.

    but what about iframes? If I write :
    [php]
    global $folder;
    echo “[iframe width=\"300\" height=\"330\" src=\"$folder/search.php\" frameborder=\"0\"] [/iframe]“;
    [/php]

    it is echoing:

    [iframe width="300" height="330" src="http://127.0.0.1/cameracoffee/episodi/search.php" frameborder="0"]

    Why the first 2 parenthesis aren’t converted?
    If I use angled parenthesis, nothing is shown…

    • Hi Francesco,

      Try using the mode=old version of the plugin for this script, there is a tag conversion upgrade coming out soon that should solve the issue though.

      An alternative is to use the snippets feature that will allow you to write your code normally.

      The < tags are removed as some paragraph tags get added automatically by default.

      Thanks,
      Jamie

  69. I have the following script in a WordPress page but it is not creating links. I’ve tried several codings but none of them seem to work. Do you know what the right code would be?

    [php]
    $user_name = “name”;
    $password = “pass”;
    $database = “db”;
    $server = “127.0.0.1″;
    $db_handle = mysql_connect($server, $user_name, $password);
    $db_found = mysql_select_db($database, $db_handle);

    echo “[p]“;
    print “[a class='alineatitel']“;
    print “[b]Noord-Brabant[/b][br][a class='content'][BR]“;
    if ($db_found) {
    $SQL = “SELECT * FROM table where provincie=’Noord-Brabant’”;
    $result = mysql_query($SQL);
    while ($db_field = mysql_fetch_assoc($result)) {
    print “[a href=".$db_field['link'] . ” class=’content’]” .$db_field['plaatsnaam'] . “[/a][br]“;
    }
    }
    else {
    print “Database NOT Found “;
    mysql_close($db_handle);
    }
    [/php]

    The result is
    [a href=http://www.domain.com/ class='content']PLACE
    instead of a working link with just showing PLACE

    • Hi Nils,

      Try using the mode=old version of the plugin for this script, there is a tag conversion upgrade coming out soon that should solve the issue though.

      An alternative is to use the snippets feature that will allow you to write your code normally.

      Thanks,
      Jamie

  70. I got a reply on a question concerning links in the script.
    You said I should activate the old version of the plugin but that didn’t help.
    Now I’ve created a sniplet but I don’t know how to implement the sniplet in a page. How do I do this?

  71. In addition to the previous message. When I want to save the settings when I activate the old version the browser does not continue after the alter.php page so the old version is not really activated. Is it possible to alter a php page and activate the old version manually?

  72. thanks for the cery quick responses. I set the php to [php mode=old] and I get an ‘unexpected >’ error.

    when I open with [php function=test]
    (I added a snippet echo ‘hello world’) it prompts “function not found”

    • Hi Nils,

      Its the function is, which is an integer which can be found on the left of the table, rather that the function name its self.

      I have just updated the plugin based on the code you have provided also, it now recognises the entire code except the array accessing inside the tag string.

      So basically, instead of writing

      echo "[p]".$myArray[0]."[/p]"

      you will need to write it as:

      $mya = $myArray[0];
      echo "[p]".$mya."[/p];

      I hope this helps.

      Thanks,
      Jamie

  73. nooooo what happened?

    I updated to the latest version and now everything is broken!!!!!

    please I have like 200 users online atm pls please fix it asap!!!!!!!

    • Hi Francesco,

      Apologies for the issues, the buggy tag system from the previous beta had been replaced and a dev echo was left in by mistake,

      this has been removed from the plugin now.

      It is important to note that beta’s are test released and you should always backup the plugin before updating, if in doubt, don’t update :)

      Thanks,
      Jamie

  74. I just installed the latest version and it’s now printing all the php as plain text on my pages.

    How do I fix this? Where can I get the previous version of the plugin?

    • Hi Michael,

      This issue has been fixed, a developer echo on line 22 of the plugin echo’ed the unprocessed content.

      Just remove the echo $content; inside the php handler function on line 22.

      Thanks,
      Jamie

  75. Rosemary Senjem says:

    Found a bug in most recent update — amazingly on the first try! I have fixed it for myself, but thought you’d want to know about it.

    Line 43 in the file called allowphp.php should be commented out like this: //echo $content; If it is left as is (un-commented), the php we are trying to hide in the post is revealed to everyone on the published page.

    Have a good day and keep up the great work!

  76. Hi I’m trying to use your plugin but having a few problems – sorry if I’ve missed something completely obvious. I’m trying to add a link to my WP page so replaced hte brackets etc. I have the below:

    [php]
    echo’[a href="http://www.testing.co.uk/test.php"]Testing page link[/a] and [a href="http://www.testing.co.uk/test123.php"]Testing page 2 link[/a]‘;
    [/php]

    This doesn’t seem to work? Thanks for any help

    • Hi Nils

      Based on the error message it appears that the query isn’t getting any results from the database, perhaps check the query first to see what is actually coming back?

      Thanks,
      Jamie

  77. PHP code inserted utilizing your Plug-in:

    [php]
    echo ‘[form]‘;
    echo ‘[input type=button value="Do Something" /]‘;
    echo ‘[/form][br/]‘;

    echo ‘[form name=anotherForm]‘;
    echo ‘[input type=button value="Do More" /]‘;
    echo ‘[/form]‘;

    test page URL: http://servants4him.staleybuild.com/?page_id=807&preview=true

    [/php]

    Using the “View Source Code” option of Firefox browser, the above code produces:

    Notice that what should be a closing tag at the end of the two forms does NOT contain a “/”.

  78. Forrest Kendall says:

    when quoted text is in the [form] tag – the line [form ....] appears on my test page as text and the form does not display.

    [input ...] tags, and [td ... ] tags, etc. exhibit the same problem.

    [php]
    echo “[form action='https://www.paypal.com/us/cgi-bin/webscr' method='post' id='PPCheckout' ]“;
    echo ‘[input type=button value="Do Something" /]‘;
    echo ‘[/form][br/]‘;

    echo ‘[form name=anotherForm]‘;
    echo ‘[input type=button value="Do More" /]‘;
    echo ‘[/form]‘;

    [/php]

    • Hi Forrest,

      Thank you for pointing this out, the issue has been found and repaired, the regex didn’t recognise hyphens in the url and so skipped the tag.

      Thanks,
      Jamie

  79. Hi:
    Since you were so prompt (THANKS!) to address the last bug that I found, here is another annoying problem …

    Subtraction in PHP code causes an error, example:

    [php]

    // this line causes an error
    $x = 5 – 2;
    echo $x . ”;

    // this line works
    $x = 7-3;
    echo $x . ”;

    [/php]

    causes the following error message:
    Parse error: syntax error, unexpected T_ECHO in /homepages/16/d114061214/htdocs/WP/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(83) : eval()’d code on line 10

    with the debug flag set (debug=1) the following code is displayed:

    // this line causes an error
    $x = 5 – 2;
    echo $x . ”;
    // this line works
    $x = 7-3;
    echo $x . ”;

    • Hi Forest,

      Thanks for pointing this out, its a dash not being translated properly and remains as a html entity at run time,

      this will be noted for the next update.

      Thanks,
      Jamie

  80. now getting this error with the test code error:

    Warning: preg_replace() [function.preg-replace]: Unknown modifier ‘:’ in /homepages/16/d114061214/htdocs/WP/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php on line 43

    [php debug=1]
    echo “[form action='https://www.paypal.com/us/cgi-bin/webscr' method='post' id='PPCheckout' ]“;
    echo ‘[input type=button value="Do Something" /]‘;
    echo ‘[/form][br/]‘;

    echo ‘[form name=anotherForm]‘;
    echo ‘[input type=button value="Do More" /]‘;
    echo ‘[/form]‘;

    // this line causes an error
    $x = 5 – 2;
    echo $x . ‘[br/]‘;

    // this line works
    $x = 7-3;
    echo $x . ‘[br/]‘;

    [/php]

  81. the regexp seems to be choking on a colon in a string.

    this code does work (relative reference to a URL)
    [php debug=1]
    echo “[a href='fee_info.html' ]test link[/a]“;
    [/php]

    this code does not work (full URL reference)
    [php debug=1]
    echo “[a href='http://www.servants4him.org/fee_info.html' ]test link[/a]“;
    [/php]

  82. Hola, estoy usando su plugin para wordpress (gracias por el aporte) Allow PHP in posts and pages, hasta ahora me funciono perfecto, pero en esta ultima actualizacion me dio un error en el archivo “allowphp.php” en su linea nº 43, exactamente lo que he hecho es borrar la barra (/) que hay despues del primer (;) y antes del (:)
    para que pueda corregirlo.

    Atentamente TDET

    • Hola TDET

      El “/” en la expresión regular es sin escape, he actualizado el plugin justo después de que se ha cargado, por lo que puede que tenga que descargar e instalar de nuevo.

      Gracias, Jamie

  83. it appears that a “/” in a URL string may be causing problems as well.

    [php debug=1]
    echo “[a href='www.staleybuild.com/fee_info.html' ]test link[/a]“;
    [/php]

    the above code displays:

    [a href='www.staleybuild.com/fee_info.html' ]test link

    and not the desired link.

  84. Regarding the “include” problem, I ran into it this morning and found a solution. I realized I needed to use a relative path, but wasn’t sure where the file was in relation to the wordpress stuff. So first I tried numerous ../../../ sequences. Let me show you:

    WordPress is installed on the root.
    The file is at website.com/files/file.php.

    I tried things like:
    include(‘../files/file.php’);
    include(‘../../files/file.php’);
    include(‘../../../files/file.php’); … and so on

    What worked was simply this:
    include(‘files/file.php’);

    Thanks for the script, love it.

    • Hi Micah,

      The is because the whole site is processed thought the index.php file in the wp-root, the permalink structure after the blog url is actually processed as $_GET variables in the index file, so when you include, your including from the index.php in the site root.

      Thanks,
      Jamie

  85. Hello,

    Just installed your plugin, and mostly works great, but running into an issue. I am getting data from a database and building a url from that. It works when I use the following:

    echo “[a href='video?=' target='window']” . $row['sub-title'] . “[/a]“;

    but I need to insert an database id number after the video?=

    for that I use:

    echo “[a href='video?=" . $row['id'] . “‘ target=’window’]” . $row['sub-title'] . “[/a]“;

    And that doesn’t work. I am assuming this is because the brackets are conflicting, I have an open bracket for href “[a href” and the code is expecting a closed bracket, but before I can close the bracket, I need to insert id from the database and am opening another bracket “[id”, and this is what’s causing the issue.

    Is my assumption correct? If so, how do I get around this. If not, what is causing the code to not work?

    Thanks for your help.

    Ray

    • Hi Ray,

      Turn any array entries into standard variables before echoing them.

      e.g. change:

      echo “[a href='video?=" . $row['id'] . “‘ target=’window’]” . $row['sub-title'] . “[/a]“;

      into

      $id = $row['id'];
      $sub_title = $row['sub-title'];
      echo “[a href='video?=" .$id.“‘ target=’window’]” . $sub_title . “[/a]“;

      This should work!

      thanks,
      Jamie

  86. Forgot to mention, I also tried escaping the open/close brackets, still didn’t work.

    Ray

  87. an email address in the following code seems to be causing a problem. The [input ...] tag is not properly decoded. You can verify this by moving the input field name “cmd” above/below the field with an email address.

    [php debug=1]
    echo ‘[form action="https://www.paypal.com/us/cgi-bin/webscr" method="post" id="PPCheckout" ]‘;
    echo ‘[input type="hidden" name="cmd" value="_cart"/]‘;
    echo ‘[input type="hidden" name="business" value="accounting@servants4him.org"/]‘;
    echo “[input name='image_url' type='hidden' value='http://servants4him.staleybuild.org/wp-includes/images/S4HLogo.gif' /]“;
    echo ‘[input type="hidden" name="upload" value="1"/]‘;
    [/php]

    see debug code that is output

  88. the following code is generated via Google Checkout for a Donation button. something is preventing it from working with PHP code.

    [php debug=1]
    echo ‘[input alt="Donate" src="https://checkout.google.com/buttons/donateNow.gif?merchant_id=341924183388020&w=115&h=50&style=white&variant=text&loc=en_US" type="image"/]‘;
    [/php]

    I assume it is the “?” or “&’s” that are causing the problem.

    Forrest

    • Hi Forrest,

      I have just updated the plugin to take into account a lot of the symbols that are found in text, and even some that aren’t, hopefully that should cover the bases.

      the only outstanding issue is the use of arrays within the string, they need to be converted to variables, simply because of the array access structure being in [ and ]‘s

      Thanks,
      Jamie

  89. Jamie:
    Thank you for your quick response on the issues I have been experiencing. The fast resolution of these issues will help us launch our new WP-based site on Dec 15. I very much appreciate your professionalism; having worked as a software developer for 30+ years.

    I gave your plug-in a 5 star (*****) rating. Great work!!

  90. Plug-in enhancement request:

    Could you provide an option when debug=1 to show line numbers in the left-hand column. This will help in finding errors in code.

    Thanks!

  91. Hi:
    your most recent fixes may have resolved the URL problems I was seeing, but seems to have created a new problem:

    [php debug=1]

    if (true && true) echo “this test worked”;
    [/php]

    the logical AND (&&) is not working correctly now.

    Forrest

  92. as a work-around for logical AND (&&) not working right now it tried using negative boolean logical to functionally do && operation using the following code:

    php debug=1 silentdebug=1]
    if (!(1 != 1 || 2 != 2)) echo “this test worked”;
    [/php]

    //if (NOT ( 1 NOT EQUAL 1 OR 2 NOT EQUAL 2))
    // the above logic worked, i.e. || parses OK

  93. false alarm on my last error report.

    I had put the editor into Visual mode and it messed up the PHP code when it saved.

    Got any clever plug-ins that will disable Visual mode for selected pages? I will look to see if anyone has developed a plug-in like this.

    Forrest

    • Hi Forrest,

      unfortunately we do not have one currently. it would also be quite difficult to set up as its a single editor page that is populated by the post/page’s content, rather than it being one editor per post/page.

      thanks
      Jamie

  94. Hi, thanks for Your work. I need to have a code where imagefile.png is determined by a php variable code inside a page. The plugin instead put the code as it is in the page, like a citation. How to make the plugin to produce that correctly (I mean as a HTML in the page)? any way to include the img tag between the allowed ? Regards

  95. Hi,
    the code that do not work is this one

    [php ]
    $Image=”http://giexperience.hostei.com/wp-content/plugins/adminer/images/logo.png”;
    echo “[img src='".$Image."']“;
    [/php]

    You can see the results here http://giexperience.hostei.com/?page_id=496

    I’ve tried many different format, but even the text neither appear.

    Any way to use images?.
    regards

  96. Jamie:
    I have PHP code that creates two forms. However, when the actual HTML is generated the [/form] tag that ends the first form does not appear to be generated. This causes the fields for the second form to be part of the first form.

    The end result is when I click on either the Paypal button or the Google Checkout button but take me to the Paypal URL.

    I have given a short version of test code below. I am using Firefox >> Web Developer >> Inspect to view the resulting HTML.

    Thanks!

  97. Jamie:
    Here is a simpler set of PHP code that exhibits the problem I am having with multiple forms.

    [php debug=1 ]
    echo ‘the Home Page button should take you to Hit Research home page[br /]‘;
    echo ‘[form action="http://www.hitreach.co.uk" id="pgHome" ]‘;
    echo ‘[input type="submit" value="Home Page" /]‘;
    echo ‘[//form][br /]‘;

    echo ‘the Contact Page button should take you to Hit Research contact page[br /]‘;
    echo ‘[form action="http://www.hitreach.co.uk/contact" id="pgContact" ]‘;
    echo ‘[input type="submit" value="Contact Page" /]‘;
    echo ‘[//form]‘;
    [/php]

  98. when PHP code is dynamically building rows and cells in a table the [/td] and [/tr] in a string appears to be creating extra cells. See following test code. The numbers in the table should under the thee headers.

    If I remove the [/td] from the string to be output I can get the desired output, but seems like there is a bug that needs to fixed.

    HEADER 1HEADER 2HEADER 3

    [php ]
    $pos = array(“left”, “center”, “right”);
    for($i=0; $i != 3; $i++) {
    $str = “[tr]“;
    for($n=0; $n != 3; $n++) {
    $x = $i * 3 + $n + 1;
    $str .= “[td align=ppp]vvv[/td]“;
    $str = str_replace(“ppp”,$pos[$n],$str);
    $str = str_replace(“vvv”,$x,$str);
    }
    $str .= “[/td]“;
    echo $str;
    }
    [/php]

  99. Jamie:
    I just looked at the problem that Loris is having http://www.hitreach.co.uk/wordpress-plugins/allow-php-in-posts-and-pages/comment-page-3/#comment-671. Her problem is she is using 3 different type of quotes.

    if you cut and paste her PHP code you can see it. when I change her quotes to either “” or ” pairs her code worked fine. But, as she wrote it, it does not work.
    Forrest

  100. Hi: I posted more problems I encountered late in the day on Dec 7. None of those comments are appearing in your blog.

  101. Hi, when I put my php in a template file it works fine but when I put it within the shortcodes it doesn’t work at all. I will attempt to paste it below, do you have any thoughts? This is supposed to produce a login prompt for name and password.

    [php]

    Login
    <form action="/wp-login.php” method=”post”>
    <input type="text" name="log" id="log" value="” size=”20″ />

    Remember me
    <input type="hidden" name="redirect_to" value="” />

    <a href="/wp-login.php?action=lostpassword”>Recover password

    Logout
    <a href="”>logout
    admin

    [/php]

    • Hi Mark,

      Please read the plugin readme, all < and > must be converted into [ and ] before use in the plugin, the alternative solution is to use the plugin’s snippets menu to add your own PHP code without the need for the conversion.

      Thanks,
      Jamie

  102. Robert Saunders says:

    Is it possible to echo a table using this.

    When I do this.

    [php]

    This

    [/php]

  103. just wanted to say “THANKS!”. This is a marvelous plugin. I have a little php file using curl to get content from another site and your plugin makes it simple to ‘include’ it into my WP site.

  104. Hello. Thank you for the plugin.

    I have one question… feeback if you can.

    I’m trying to send simple values like $id=’someid’ from the current post to the single.php of my wp, well, the plugin does the job, works great inside the post, but im not getting any data in that include that i’m talking about.

  105. I cant seem to get this link to work. The php works when its not placed in the link. Any ideas?

    user_login;[/php]” title=”Share on Facebook” target=”_blank”>

  106. a href=”http://www.facebook.com/sharer.php?u=http://myurl.co.uk/?affid=[php]global $current_user; get_currentuserinfo(); echo $current_user->user_login;[/php]” title=”Share on Facebook” target=”_blank”>

  107. Hi Mentha,

    You may need to get the values as session variables or use query strings for the value to become available in other files.

    thanks
    Jamie

  108. Hi Martin,

    Try echoing the entire link as part of the php function, so something like

    [php]
    global $current_user;
    get_currentuserinfo();
    $login = $current_user->user_login;
    echo “[a href='http://www.facebook.com/sharer.php?u=http://myurl.co.uk/?affid=".$login."' title='Share on Facebook' target='_blank']“;
    [/php]

    Hopefully this will work for you.

    Thanks
    Jamie

  109. HELP PLEASE! I am having a heck of a time trying to get this sql to work. I feel like I have tried everything.
    This is what I have come down to:
    [php debug=1]
    include “include/dbconnect.php”;
    $sql = “SELECT *
    FROM properties
    WHERE (property_status = ‘Active’ || property_status = ‘Pending’)”;
    if ($_POST['property_type'] != “”) $sql .= ” && (property_type like ‘$_POST['property_type']‘)”;
    if ($_POST['sortBy'] == “Acreage” || $_GET['sortBy'] == “Acreage”) { $sql .= “ORDER BY property_acreage”; }
    else {
    $sql .= “ORDER BY property_title”;
    }
    $sql .= “”;
    $result = mysql_query($sql);
    $numResults = mysql_num_rows($result);
    [/php]

    and I am getting this error

    Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/mencom/public_html/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(83) : eval()’d code on line 6

    This is urgent! I was supposed to have this working days ago but I just can’t seem to get this to work! Thanks for your help

  110. Hi There,
    A very simple help for you !

    I need to write a clickable link for to a web site
    I tried different way reading all the posts without success … could you help me ?

    THX a lot
    Maurizio

  111. Hi Michelle,

    the error you are seeing is from the call to the $_POST array within a string, you should either concatenate the string, or add the value to a variable before using it in a string. For extra security you should also make use of the $wpdb class rather than using your own.

    Thanks,
    Jamie

  112. Hi Maurizio,

    An example link would be:
    [php]
    $href = “http://url”;
    $class = “Class_not_mandatory”;
    $target=”target_not_mandatory”;
    $id=”your_id”;
    echo “[a href='$href' target='$target' class='$class' id='$id']Link text[/a]“;
    [/php]

    obviously you can set the link attributes yourself, and you can even leave some out.

    Hope this helps,

    Thanks,
    Jamie

  113. I have been trying to get the following to work and can not seem to get it. The end result does not show the opening a tag as a link tag but instead like so:

    [a href=""]97805

    [php]
    while($row = mysql_fetch_assoc($getCourses)) {
    echo ‘[a href="';
    echo $row['sectionID'];
    echo ‘”]’;
    echo $row['sectionID'];
    echo ‘[/a] | ‘;
    }
    [/php]

  114. Hi Brian,

    The [ ] conversion only works when they are together in the same statement,

    For your statement you can use < and >‘s instead.

    Thanks
    Jamie

  115. horror story of this plugin

    some example.
    1) echo “hello world”;
    generate hello world
    2) one defined function not usable in second and another block

    [php]
    function GET_DATE_FROM($content,$datum)
    {
    $fileLines = explode(“\n”, $content);
    $datum = $fileLines[0];
    $content = str_replace($datum,””,$content);
    return $datum;
    }
    global $datum;
    $page_id = 320;
    $mypages = get_page($page_id);
    $page_data = get_page( $page_id );
    $content = apply_filters(‘the_content’, $page_data->post_content);
    $datum = GET_DATE_FROM($content,$datum);
    echo $datum;
    $content = str_replace($datum,””,$content);
    [/php]

  116. Hi Kresimir,

    I’m not quite sure what you are meaning here, I tested your function and it was all okay, each php block is evaluated separately are not linked in anyway, There are plans for a workaround in the near future however.

    Thanks,
    Jamie

  117. I placed the following short code in my home page:

    [php]
    dynamic_content_gallery();
    [/php]

    Received the following error message in an error_log file created on the server:

    [13-Jan-2012 07:27:16] PHP Parse error: syntax error, unexpected $end in /home1/myonlin7/public_html/mylocalcommunitynews/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(83) : eval()’d code on line 4

    So Chris, if what you are saying is correct, the problem is originating from Dynamic Content Gallery for WordPress and I should contact them?

  118. I am trying to build a dropdown list based on values in a database. Connections are all fine. Here’s the code (nested inside an HTML table):

    [php]
    $sql = ‘SELECT * FROM T_ACCOUNT ORDER BY FIRST_NM’;
    $result = mysql_query($sql) or die(mysql_error());
    $name_select = ‘[SELECT NAME="ACCOUNT_ID"]‘;
    while($row = mysql_fetch_array($result))
    {
    $name_select = $name_select . ‘[option value="' . $row\['ID'\] . ‘”]’;
    $name_select = $name_select . $row\['FIRST_NM'\] . ‘ ‘ . $row\['LAST_NM'\];
    $name_select = $name_select . ‘[/option]‘;
    }
    $name_select = $name_select . ‘[/SELECT]‘;
    echo $name_select;
    [/php]

    I am using [ and ] for , and when I actually want [ or ] I am escaping them using backslash (like \[ and \]). Here’s my output:

    [option value="5"]Alberto Gueco[option value="12"]Angelo Gudiel[option value="32"]Angus Beaton[option value="0"]Anonymous Joe[option value="18"]Ben Aplin……etc, etc, etc.

    And it ends with:

    [option value="4"]Yasaman Sabersheikh

    I have tried using for the [option value="#"], but it just fails to generate anything in that case. I also tried putting a space between < and / for the ending tags (like …had to use here) but it just came up as a non-tag, plain text.

    What am I doing wrong?

  119. Hi Daryl,

    What version of the plugin and tag replacement system are you using? it may be that the square brackets for the options may work as < and >‘s instead.

    Thanks,
    Jamie

  120. I actually ***just*** updated the plugin imediately prior to posting that (and re-tested, of course), so it would be the most recent version. I can confirm this tomorow, however.

    First, it doesn’t look like my post came through fully. Sorry about not checking that earlier. Are you able to see what I added initially? (prior to the proper html tags’s getting stripped out?)

    For the option tags, I initially was using and it wasn’t working. I switched to [] and started to see the ending option tags, but not the gegining ones.

    Hmmmmm. Starting to be a little confusing here. Maybe I’ll try to re-post my origonal post with the actual tags showing up. Is there a trick to adding comments with php/html in them?

    • Hi Daryl,

      if it is the very latest version, you should just try writing your PHP as normal, using the correct syntax,
      then wrap it in the PHP shortcode as normal, but with a twist, use the following shortcode tags:

      [php useadvancedfilter] php code [/php useadvancedfilter]

      If that works, let us know :)

      Thanks,
      Jamie

  121. That worked like a charm. Thanks!

    Is there any documentation I can review re: useadvancedfilter?

    Also, I’m still having trouble with using the form overall. After the post, none of the variables register as having been set. If I change it to use get instead, I get re-driected to my homepage, but the URL does contain the proper key/value pairs. I will need to debug fully after having fixed this latest issue, but I figured I’d put it out there. Any thoughts?

  122. Hi Daryl,

    the useadvancedfilter feature is a new experimental feature we are testing out, because of this, it is not compatible with code snippets or the debug mode currently.

    The advanced filter is able to process standard PHP syntax inside of the shortcode, which is about the only thing that sets it apart from previous versions.

    With regards to the form issue, try ensuring that the action page set in the form tag definitely exists, as POST and GET variables can sometimes be lost due to the permalink redirects.

    Thanks,
    Jamie

  123. Hi, i want to restrict other users except me about using [php] tags. What can we do?

    • Hi Omer,

      As with most shortcodes, you cannot currently prevent other users from using them as it executes when the post/page is viewed, so if you were only to let yourself use it, any visitors and restricted users would only see the shortcode output rather than the parsed php.

      Thanks,
      Jamie

  124. I’ve added a snippet like: if (function_exists(‘wpfp_link’)) { wpfp_link(); }
    and saved it. but when I deleted that snippet, it showed that the snippet was deleted. but the function is still working. now how can I delete that snippet permanently?

    • Hi Taitur,

      by deleting a snippet though the plugin options page, it removes it from the database so it can no longer be used, however, some cache plugins may save the final output to the page, so when you view the page you are actually viewing the cached version, if this is the case, you may need to purge your cache.

      Thanks,
      Jamie

  125. Hello,

    I’m having a problem with echoing [/select]. see:
    echo ‘[/select]‘;

    This echos nothing.
    I can echo ‘[select]‘;
    I can also do the following, successfully:
    echo ‘[option id="' . $runner->RunnerID . '"]‘ . $runner->RunnerName . ‘[/option]‘;

    Any thoughts on echoing [/select]? Using version 2.3

    Thanks!

    • Hi Kyle,

      Try using
      [php useadvancedfilter]
      //normal php echoing//
      echo “<select>”;
      //echo your options
      echo “</select>”;
      [/php useadvancedfilter]

      This should work :)

      Thanks
      Jamie

  126. does your plugin support multisite? I can create a snippet if on the network main site, but not when on sites within my multisite. Also, I am trying to place openx code- which is PHP in the bottom a blog post and nothing shows up – I tried with [php] brackets

  127. Hi Talynndar,

    Currently the plugin is only built to support the single installations of WP, however a MU version is something that is in consideration.

    R.E the openx code, try using the latest version of the plugin and the experimental [php useadvancedfilter] php code [/php useadvancedfilter] shortcode.

    Thanks,
    Jamie

  128. Hi Jamie,

    I’m glad to see this thread is still alive. I’ve been successfully using the php plugin to include a php file that resides up a directory from my blog. If you look at the comments for this thread circa late Jan 2011, you’ll see my questions and your excellent help on this subject. Well, with recent updates, something has been broken now.

    I was using this syntax for the past year to include a contact mail form:

    [php]
    include(‘../dir/myform.php’);
    [/php]

    It worked fine, but now, with the lastest updates, it does not. It almost appears the new php plugin won’t allow files outside a directory. It works fine for those includes I have inside the top level of the blog directory, just not those in directories above.

    Using your advice from you discussion a year ago, I also tried this syntax:

    [php]
    $root = realpath($_SERVER["DOCUMENT_ROOT"]);
    //echo $root;
    include(‘$root/dir/myform.php’);
    [/php]

    But that too does not work. The form simply does not render anything. It is as if the file is never included/called.

    Any ideas?

    Thanks,
    Derek

    • Hi Derek,

      Thank you for your comment.

      Nothing has changed with regards to the handling of PHP functions, except some minor regex syntax changes.

      I have tested your provided syntax against the new regex and it all is fine, could something have changed in your php version?

      With regards to the alternative syntax, the include string that uses a variable : include('$root/dir/myform.php'); This needs to be a double quoted string, or have the /dir/myform.php as a string concatenation to the variable, as single quotes acts as a literal string, so it doesnt insert the variable content, see: http://php.net/manual/en/language.types.string.php for more information

      Hope this helps,

      Thanks,
      Jamie

  129. Love this plugin, but a few issues with some of the updates.

    I’m a web designer and I share a lot of source code and now all of my normal PHP examples are actually executing. Everything was perfect when the PHP needed [] to execute (this is a good precaution).

    But, now all my normal PHP using is actually executing. I’ve checked “Use the old version (pre 2.2.0) code replacement method” which doesn’t fix the issue.

    Can I expect a possible fix or should I just downgrade to:

    http://downloads.wordpress.org/plugin/allow-php-in-posts-and-pages.1.2.3.zip ?

    (which appears to be the closest previous stable version available)

    Thanks, Bryan

  130. HOW TO GET PHP POP-UP FORM TO WORK ON PAGE?

    HOW TO GET PHP POP-UP FORM TO WORK ON PAGE?

    Hello

    How do I get my Registration Form to work on my Home Page using the
    php tags. [php] [/php]
    Here is my code below:

    Regards,
    Rich
    email: richo@yimusiconeuniverse.com

    ======================================================================

    <link rel="stylesheet" href="/popupjquery/general.css” type=”text/css” media=”screen” />
    <script src="/popupjquery/jquery-1.2.6.min.js” type=”text/javascript”>
    <script src="/popupjquery/popup.js” type=”text/javascript”>

    • Hi Rich,

      Using the latest version of the plugin you can add
      [php useadvancedfilter]
      echo ‘‘;
      [/php useadvancedfilter]
      This will write the styles and scripts onto the page in the location of the php tag.

      thanks
      Jamie

  131. Hi Jamie,

    First of all, thank you for your work.

    Am a bit desperate trying to run php on my blog, am running into a weird problem :

    the php executes correctly but then the menu bar as well as the sidebars’content of the page/post which contains php code just vanish. It appears back again once I deactivate the plugin.

    I have tried Exec-PHP plugin as well but with exact same outcome…I have tried to get some help on different forums but no one replied.

    So I tried deactivating all plugins but the php one to see if there any inter-plugin conflicts…still it didn’t work..
    I have also tried other WordPress themes, but it didn’t work out again.
    I have tried to look if other people got the same issue, found couple, but every time topic was closed without any reply…

    Am developing locally using Xampp, WordPress 3.3.1, Custom Theme for Artisteer, any help would be greatly appreciated.

    • Hi Nairn,

      Thank you for your comment,

      The first thing to check is that your outputting valid code, for instance, the PHP code you outputting could be leaving an open DIV tag, which acts like a void and sucks in the rest of the page,
      The next think to check is that your PHP is correct, and doesn’t contain any syntax errors, if this is the case, a syntax error would cause the page to completely stop loading and output an error message,

      So, try first copying the sourcecode of your page and putting it though a validator like W3C Markup Validation Service and if that reports back no unclosed elements, try turning on wp_debug in the wp-config.php file and seeing if it outputs any fatal error messages.

      I hope this helps,

      Thanks,
      Jamie

  132. Hi Jamie,

    I know it’s been awhile since the last post, but I was wondering if this plugin has known issues with WordPress Version 3.3.1? I’m having issues inserting my code. The page times out when I insert any PHP code

    • Hi Cesar,

      There have been no reported issues with 3.3.1, could it be your install, as I have previously updated WP sites to 3.3.1 and elements such as the image uploader completely stopped working.

      Try downloading a testing environment like EasyPHP, and installing a fresh version of 3.3.1 and seeing if it works :)

      Thanks,
      Jamie

  133. Hi Jamie,

    Thank you for your feedback :)

    It doesn’t seem I’ve got any messed up code using the W3C validation service.

    I’ve removed some lines in the php code and it displayed everything back again.

    Below is the old php code that was causing the page to omit the menu bar and the sidebars’ content :
    [php]
    mysql_connect(“localhost”, “root”, “”) or die(mysql_error());
    echo “Connected to MySQL [br/]“;
    mysql_select_db(“test”) or die(mysql_error());
    echo “Connected to Database: Test”;
    [/php]

    Below is the edited php code :
    [php]
    echo “Connected to MySQL [br/]“;
    echo “Connected to Database: Test”;
    [/php]

    It seems the “CONNECT” and “SELECT” MySQL keywords were causing the whole trouble, since the php code executed normally once I got rid of them.

    Php works fine but not MySQL keywords which seem to somehow stop the page to load completely??

    • Hi Nairn,

      I notice you have the OR Die() code, could it be that its failing to connect or select db?

      If you are using the latest version of the plugin, try this and see if it works:

      [php useadvancedfilter]
      mysql_connect("localhost", "root", "") or die(mysql_error());
      echo "Connected to MySQL <br />";
      mysql_select_db("test") or die(mysql_error());
      echo "Connected to Database: Test";
      [/php useadvancedfilter]

  134. Hi Jamie,

    I’ve finally got the hang of it, so I’ll put the answer down here in case anyone drops for the same issue.

    Actually, I have just added 2 lines on the php code asking to connect back to the main wordpress database since the ‘test’ database was OUTSIDE the main wordpress database and this is what was causing the page to not load completely because wordpress couldnt get access to its own database to finish loading the entire page :D

    Here are the 2 lines added to the previous code :

    mysql_select_db(“wordpress”) or die(mysql_error());
    echo “Connected to WordPress Database”;

    Thanks again for the help Jamie, you put me in the right direction :)

  135. Hi Jamie,

    I like your plugin very much, but now I have a problem. I would like to combine the plugin with formidable pro:

    [formresults id=11 cols=3 user_id=[php] echo “2″;[/php] ]

    but it is not working. Is there a solution?

    Thanks
    Eddi

  136. I solevd it, Now I am using [php useadvancedfilter] instead of [php] and it workes. Even within the shortcode :-)
    Thanks for your help!!

  137. Hi, I looked at one of my sites, http://home.allpurposeguru.com, and found this message instead of the expected front page:

    Parse error: syntax error, unexpected T_ENDFOREACH in/my/path/to/public_html/home/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(43) : eval()’d code on line 29

    That appears to be your plugin. Can you tell me how to fix the problem?

    • Hi David,

      What is the code that you are using?

      Thanks,
      Jamie

      • I don’t know. The only thing I can find is where I can edit the plugin. I know a little HTML and basically nothing else about coding. Someone else coded my page, and that company tells me the problem is in the plugin.

        Here’s the beginning of what I can find. If I started copying in the right place, line 29 is included:

        add_shortcode(‘php’,’php_handler’);
        add_shortcode(‘PHP’,’php_handler’);
        add_shortcode(‘allowphp’,’php_handler’);
        add_shortcode(‘ALLOWPHP’,’php_handler’);
        add_action(‘admin_menu’, ‘allow_php_menu’);
        add_filter(‘widget_text’, ‘do_shortcode’);
        add_filter(‘the_content’, ‘apip_advanced_filter’,0);

        register_activation_hook(__FILE__, ‘allowPHP_activate’);
        global $dbVersion;
        $dbVersion = “1.0.0″;

        define(“ALLOWPHPVERSION”,”2.3″);
        define(“APIP_URL”, WP_PLUGIN_URL.’/’.str_replace(basename( __FILE__),””,plugin_basename(__FILE__)));

        function apip_advanced_filter($args){
        $options = get_option(“allowPHP_options”);
        if(isset($options['use_advanced_filter'])){
        if($options['use_advanced_filter'] == “1″){
        remove_shortcode(“php”);
        $args = str_ireplace(“[php]“,””,$args);
        $args = str_ireplace(“[php useadvancedfilter]“,””,$args);
        ob_start();
        eval(“?>”.$args);
        $returned = ob_get_clean();
        return $returned;
        }
        }
        $args = str_ireplace(“[php useadvancedfilter]“,””,$args);
        ob_start();
        eval(“?>”.$args);
        $returned = ob_get_clean();
        return $returned;
        }

  138. James Marr says:

    Hi,

    I have used two peices of code on a WordPress page but only one of them is working.
    [code]
    [php] $caseStudy = $_GET["cs"];
    switch ( $_GET["cs"] ) {
    case "case-study-one" :
    $csImage = "cs1.jpg";
    break;
    case 'case-study-two' :
    $csImage='cs2.jpg';
    break;
    }
    [/php]
    Thank you for choosing to download the [php] echo ucwords($_GET['cs']);[/php].
    [/code]

    Only the last php code works. It successfully echo’s the name of the case study in the very last line but the switch statement doesn’t work and the first two echo statements are empty. I can echo $_GET['cs'] but not if I use the variable that contains it. neither will it echo any value for $csImage;

    Any help greatly appreciated.

    James

    • James Marr says:

      Soory, there’s a line missing form the code above…

      This should have gone before the “Thank you for choosing…” and is the code in question:

      a href=”http://www.vocal.co.uk/wp-content/themes/vocal2012/images/downloads/case-study-[php]echo $csImage;[/php]”

      (I’ve removed the opening and closing brackets on the a tag in case this is what stopped it from displaying above.

      • Hi James,

        Variables do not carry from block to block unless you are using the advancedfilter feature, this can be used by updating to the latest version of the plugin and using the tags: [php useadvancedfilter] and [/php useadvancedfilter], then you can use normal PHP syntax as well.

        Hope this helps,

        Thanks,
        Jamie

  139. Hi Jamie,

    Excellent plugin. This plugin has saved me lots of time and hassle as I use it quite extensively.

    However, now I’m getting a baffling error. I’ve read through all the comments on here, and found only one other person (Stefan on March 28, 2012) that is experiencing the same error (but no solution has been posted yet). Here’s my code:

    [php]
    //If we submitted the form
    if(isset($_POST['submit']))
    {
    echo “form submitted”;
    }
    //If we haven’t submitted the form
    else
    {
    [/php]

    Name

    [php]
    }
    [/php]

    And the errors:

    Parse error: syntax error, unexpected $end in /[path removed]/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(110) : eval()’d code on line 10

    Parse error: syntax error, unexpected ‘}’ in /[path removed]/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(110) : eval()’d code on line 2

    Am I doing something wrong, or is this a newfound bug?

    Thanks!

    • Hi Marvin,

      Thank you for your comment,

      As a general rule when it comes to the plugin as the shortcodes are parsed separately, and not combined, brackets cannot be split between the two shortcodes,

      however, if you are using the latest version, you can split the brackets between codes if you use the following: [php useadvancedfilter]//your code goes here + { [/php useadvancedfilter] Name [php useadvancedfilter] } [/php useadvancedfilter]

      This will make the shortcode behave more link a php tag than previously, however the tag replacement system is no longer used, so you will need to write it in correct php syntax.

      Hope this helps,

      Jamie

      • Thanks Jamie!

        That fixes it.

        Once again, AWESOME plugin, and equally, if not more, awesome support!

        Thanks man!

  140. Hi guys,

    Love the plugin.

    Busy converting my sites from using exec php, largely due to the level and quality of your support!!!!!!!

    As a php neanderthal the useadvancedfilter option has saved me problems with converting some php code which goes beyond the obscure (for me).
    Basically allows me to treat it as a black box.
    Wrap it in shortcode tags and use the filter – happy days!
    Good stuff!!!!

    Have some smaller requirements which you guys may be able to help with, would be confident and happy to discuss based on what is seen here.

  141. Panagiotis says:

    Is there any way to check if php code is running from within WordPress? Please note I use include.

    • Hi Panagiotis,

      I’m not quite sure what you are meaning here, you can test to see if it is including the file by using require rather than include, as the script will exit if it cannot include the required file.

      Thanks
      Jamie

  142. I guess I should have read a bit further in the comments to see that variables don’t carry from block to block unless you use “php useadvancedfilter”. Next time I’ll read before asking questions. Great Plugin comes in handy for all types of things!

  143. I really appreciate all your hard work. I’m sooo close to getting this code to work, but I keep getting errors thrown my way. Here is the code I’m using:
    [php]
    include_once(ABSPATH . WPINC . ‘/feed.php’);

    $rss = fetch_feed(‘http://twitter.com/favorites/bballsource.rss’);

    $maxitems = $rss->get_item_quantity(3);

    $rss_items = $rss->get_items(0, $maxitems);
    [/php]

    [php] if ($maxitems == 0) echo ‘No items.’;

    else

    // Loop through each feed item and display each item as a hyperlink.

    foreach ( $rss_items as $item ) : [/php]

    [a href='[php] echo $item->get_permalink(); ?>’]

    [php] echo $item->get_title(); ?>

    [/a]

    [php] endforeach; ?>

    I’ve tried to go through as many comments as I can from above, but I’m hoping you’ll see the issue right away and explain to me how dumb I am.

    This is the error: Parse error: syntax error, unexpected $end in /hermes/bosweb/web121/b1216/ipw.willwork/public_html/www.bballbreakdown.com/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(110) : eval()’d code on line 6

    and here is the URL:http://www.bballbreakdown.com/in-game-tweets/

    A thousand thank you’s!!

    • Hi Nick,

      As suggested with all recent code help requests, try using the [php useadvancedfilter] //code [/php useadvancedfilter] tags and writing your code as standard PHP, this should do the trick :)

      Just make sure your using the latest version of the plugin!

      Thanks,
      Jamie

      • Thanks for the reply. Alas, it didn’t work. I’ve got version 2.3 installed.
        One question: Does it matter if I create the code in Visual or HTML? I tried both, but no joy.

        Any other suggestions? THANKS JAMIE :)

        • Hi Nick,

          it requires your code to use the correct syntax for php, but doesnt matter so much if its done in visual or html, but to be on the safe side, it should probably be done in html.

          What is the code that you are using with the advancedfilter tag?

          Thanks
          Jamie

          • Here’s what I’ve put in the HTML window:

            [php useadvancedfilter]
            get_item_quantity(3);
            $rss_items = $rss->get_items(0, $maxitems);
            ?>

            <?php if ($maxitems == 0) echo 'No items.’;
            else
            // Loop through each feed item and display each item as a hyperlink.
            foreach ( $rss_items as $item ) : ?>

            <a href='get_permalink(); ?>’>
            get_title(); ?>

            [/php useadvancedfilter]

            Here’s the error:
            Parse error: syntax error, unexpected ‘<' in /hermes/bosweb/web121/b1216/ipw.willwork/public_html/www.bballbreakdown.com/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(43) : eval()’d code on line 2

            THANKS SO MUCH!

            • Hi Nick

              I have noticed that you do not end the foreach loop after: // Loop through each feed item and display each item as a hyperlink.

              Also with the advanced filter tag, [php useadvancedfilter] and [/php useadvancedfilter] act as < ?php and ?> respectively, so the use of it at the end closes the php tag which is already closed :)

              Hope this helps

              Thanks
              Jamie

              • Thanks, Jamie. I noticed the code from my post doesn’t have the whole code – is it because you edited it?

                I still can’t get it to work, unforunately – it does appear there’s a ?> which closes the foreach loop… but I’ve gotta refresh my memory on syntax

              • Hi Nick,

                Try this:

                [php useadvancedfilter]
                get_item_quantity(3);
                $rss_items = $rss->get_items(0, $maxitems);
                [/php useadvancedfilter]

                [php useadvancedfilter] if ($maxitems == 0) echo ‘No items.’;
                else
                // Loop through each feed item and display each item as a hyperlink.
                foreach ( $rss_items as $item ) : [/php useadvancedfilter]

                [php useadvancedfilter]
                endforeach;
                [/php useadvancedfilter]

                it shouldn’t matter if you are previewing or publishing :)

                Thanks,
                Jamie

              • Also- does it matter if I’m previewing the post as opposed to publishing it? 1,000 thanks!

  144. Please, replace [ php ] to [ phpexec ]. Shortcode [ php ] was used by all hightlighters.

    • Hi gltrinix,

      We are not changing the shortcode for the plugin as that would require all the shortcodes to be changed for all users, everywhere it has been used, which is simply unfeasible.

      The plugin does offer an alternative allowphp shortcode by default already anyway.

      Thanks
      Jamie

  145. I’m trying to get this code to work in my post

    [php]
    echo “”;
    //Processing Scripts
    include ‘cf/news/news_lib.php’;
    if(!$xml=@simplexml_load_file($url2)){
    echo (“Please try again in 30 seconds.”);
    } else {
    //Print or Screen Display
    $print = “no”;
    news_article($xml,$newsId);
    }
    echo “Caravan Finder Ltd © Copyright “.date(‘Y’).”Information contained on this page is proprietary. The owner claims copyright and database rights in the same. All rights reserved.For the avoidance of doubt you must not use or attempt to use any automated program (including, without limitation, any spider or other web crawler) to access our system or this website, or to search, copy, monitor, display or obtain links to any other part of this website. Obtaining access to any part of our system or this website by means of any such automated programs is strictly unauthorised.”;
    echo “”;
    [/[php]

    What am I doing wrong here?

  146. In addition to my previous comment, I get the following error once previeweing the page;

    Parse error: syntax error, unexpected ‘[‘ in /home/adriacar/public_html/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(110) : eval()’d code on line 6

  147. hello
    Man, what an awesome job you have done here, I really need your help, this is the code I need to put in a post, I tried to change all the php open and close tags with your plugin ones but didnt work
    Could you please let me know what is the solution
    Ill for sure buy you a lot of beers after this
    Thank you!

    ‘post’,
    ‘post_status’ => ‘publish’,
    ‘posts_per_page’ => 5,
    ‘caller_get_posts’=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) { ?>

    a1
    1234
    have_posts()) : $my_query->the_post();
    $estrenoargentina = get_post_meta($post->ID, ’1′, true);
    $estrenoespana = get_post_meta($post->ID, ’2′, true);
    $estrenocolombia = get_post_meta($post->ID, ’3′, true); ?>
    <a href="” title=”Permalink to ” rel=”bookmark”>

  148. Hi,

    The plug-in won’t work for me.

    I’m not an expert in .php so…

    (1) Created config.php with:

    (2) In single.php updated to:

    (3) Created a new post and inside HTML view added:

    [php]

    [/php]

    I just want this code to be executed in my WordPress posts and it won’t work.
    What am I doing wrong…

    config.php and single.php are at the same directory
    When I view post nothing happens…no error of any kind.

    Also, I’ve seen this little “Allow PHP” icon when editing a post…what is it? Do I need to use it?

    Thanks.

  149. I get an error code when I try and run this..

    error code:
    Parse error: syntax error, unexpected $end in /home/seahawkh/public_html/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(110) : eval()’d code on line 1

    Code:

    how would I fix this?
    Thanks for the help

  150. how can i insert into the taf [php] the function ” “?
    if i write this: [php][/php] don’t work.
    sorry but i not understand the php code. thank you so much.

    • Hi Luca,

      it appears that some of your code has been stripped out when adding in to the comment editor.

      if the code isn’t executing as expected, try using the [php useadvancedfilter][/php useadvancedfilter] tags instead.

      thanks
      Jamie

  151. Is it possible to define a Code Snippet and set a PHP variable in it that can be accessed in other function within the theme code?

    If so, how could that be done?

    • Or better yet this is what I’m trying to accomplish.

      I want to create a code snippet like the following and be able to access the array contents from another function inside my theme code. Right now I use a function, but it would be nice to change the code snippet code to make certain changes (like to a CASE statement that will change often) instead of editing the function I now use.

      Code Snippet

    • Hi Glenn,

      It appears that your code has been removed by the comment form, however, you could try either a) reading the snippet direct from the database and parsing it with eval() or b) make the snippet return its values as an array, then use the do_shortcode function (http://codex.wordpress.org/Function_Reference/do_shortcode) to get the values from there and assign it to a variable.

      Hope that makes sense :)

      Thanks
      Jamie

  152. I’m having trouble closing div elements. If I process the code

    [php
    echo '[div style="width:15%; float:left;"]‘.$events[$i]->event_type.’[/div]‘;
    [/php]

    The closing loses its slash – and page formatting goes bonk. The page code looks like this:

    League

    Any fix for this? Am I just doing something wrong?

    What is a snippet and how do I create one? That might solve it for me.

    • Hi John,

      We are looking to remove the tag replacement system soon completely,

      try writing all your code as you would in a normal php file, then use the [php useadvancedfilter][/php useadvancedfilter] shortcode instead,

      this has proven to be far more effective than the replacement system :)

      Hope this helps,

      Thanks
      Jamie

  153. This post lost some content in processing. The words ‘div’ were dropped a few times. Here the code after plugin processing without start and end angle brackets – imagine if you will….

    div style=”width:15%; float:left;”>League<div

  154. After implementing the plugin I have gotten partial php code parse as i wanted to include some php that has some advanced setup, I didnt liked the displey of content page so i tried advanced option, then I got all sort of problems, 500, timeout, no connect to database..etc then I removed plugin manualy deleted from plugins as I culdnt do it from dashboard,, samething.. then i removed table from WP database. then my site index get slow partial display. But dashboard isnt navigational. I tried to replace .htaccess file but same thing, what can i do? can you help me with logining in etc, thank you.

  155. Hi Jeremy,

    Great plugin and the idea of executing php inside wp pages and posts – pretty great. I just installed it and wanted to test out a simple “hello world”, but it’s giving me the following error:

    Parse error: syntax error, unexpected ‘&’ in /home/content/31/9363831/html/UZF/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(110) : eval()’d code on line 2

    Here is my code:

    [php]

    echo “hello”;

    [/php]

    is there anything i’m doing wrong?

    Thanks! Would appreciate your help!

  156. Dear Support.

    I wonder if you would be so kind as to assist me with something?

    For several days I have been trying to add an email contact form to my web page, and so have been testing it first on a new page, but all I try, it does not send the email to the email address which I have specified for that in the PHP.

    My PHP is here: http://www.cirbroadcasting.com/life/?page_id=387

    The test form is here: http://www.cirbroadcasting.com/life/?page_id=385

    Any assistance you can provide would be very much appreciated.

    Thanks.
    Jeff Weatherhead

  157. Is the plugin still working with WordPress 3.4 ?
    Thanks !

    • Hi Gael,

      While the plugin hasn’t been tested by us in 3.4, there hasn’t been any critical updates that would stop the basic plugin functionality from working,

      so it should work :D

      Thanks,
      Jamie

  158. Hi Jamie,

    I can use your allow php in posts and pages all the time but I can’t after I moved my wordpress blog to a new host.

    Everytime I try to add code snippet, I will be redirect to the 404 page. the url is /wp-content/plugins/allow-php-in-posts-and-pages/alter.php

    I don’t know whether I did anything wrongly here.

  159. I got error :
    Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE in allow-php-in-posts-and-pages/allowphp.php(110) : eval()’d code on line 1

    110 line : eval ($content);

  160. I’m having an issue with html tags being lost, and I wonder if this plugin is responsible.

    I’m calling html from a database table, and using this plugin to display the html. But certain tags (all span tags, and various others) are being removed before the html is displayed.

    I’ve tried changing the html from to [ ] but that did not change the result.

    Any help would be appreciated. Thanks.

    This is what is sent from the db:

    For all .. that ALL games .. child's name.  Children ..
    During our summer program we have a set time

    AND this is what is sent to the browser:

    For all .. that ALL games .. child’s name.  Children ..
    During our summer program we have a set time

    • argh. I wasn’t thinking. Reposting, with html tags visible:

      this is what is sent from DB:

      For all .. that ALL games .. child's name.  Children ..
      During our summer program we have a set time

      this is what is sent to the browser:

      For all .. that ALL games .. child’s name.  Children ..
      During our summer program we have a set time

  161. re my previous two messages: problem solved. user error. sorry.
    I love this plugin!

  162. Felipe Moslavacz says:

    Hello!

    I’m having trouble with the plugin when I add two blocks of php code In a post page.
    The code is kind of a loop with database rows, but I want to keep some part of code In static HTML, without put everything in ECHO, Is It possible?

    Thanks alot.

    • Hi Felipe,

      When using the plugin using the [php useadvancedfilter][/php useadvancedfilter] shortcode tags, the code can be split up on the page and variables carried between blocks, however when using the plugin with only the standard [php][/php] tags, all variables cannot be accessed outside the block.

      e.g.

      [php]
      $a = 0;
      [/php]
      [php]
      echo $a;
      [/php]

      the $a will echo undefined.

      however with:

      [php useadvancedfilter]
      $a = 0;
      [/php useadvancedfilter]
      [php useadvancedfilter]
      echo $a;
      [/php useadvancedfilter]

      the $a will echo 0

      I hope this helps.

      Thanks
      Jamie

  163. Jennifer Davis says:

    I need to put another shortcode inside the [php] … [/php].

    [php]
    ….
    echo ‘[another shortcode]‘;
    [/php]

    And it keeps getting converted to

    instead of keeping the brackets for the other shortcode.

  164. Jennifer Davis says:

    your comment form removed part of my post.

    the plugin won’t allow me to include another shortcode inside the [php] … [/php] brackets. I’ve tried every conceivable way of escaping the brackets for the other shortcode, but the brackets keep getting converted to

    • Hi Jennifer,

      The echoed shortcode will only appear on the page in the square bracket form. you need to use the api function do_shortcode with the square brackets being escaped with backslashes.

      Alternatively use the advanced filter feature and just echo the shortcode as previously done, without the need for escaping:


      [php useadvancedfilter]
      ….
      echo ‘[another shortcode]‘;
      [/php useadvancedfilter]

      Hope this helps,

      Thanks
      Jamie

  165. Trying to use your plugin but i get some errors: Parse error: syntax error, unexpected ‘<' in /home/sabaiweb/public_html/jomtienbeach.info/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(110) : eval()'d code on line 1

    I am using this php code:

    What is wrong?

    • Hi Sabai,

      Without being able to see the code I cannot really help;

      I suggest you check the syntax of your code, and if there still doesn’t work, try using the useadvancedfilter method noted in other comments :)

      Thanks
      Jamie

  166. This code:

    $$$$$$

    Remove the dollar signs…

  167. That didn’t help, send me an email if you want to look at the php code..

  168. Having difficulties in getting shortcodes to work. Video Embeedder, By Kristoffer Forsgren , uses shortcodes like [youtube]youtubeID[/youtube].

    Unfortunately, I have tried both the escape method and do_shortcode method described in your threads. So far my many hours of trying all sorts of variations, has not come up with working code.

    The basic code layout ………….. neglecting the striping of []
    [php]
    $testvids = array(“3f9QkEalfY8″,”FtyU7UXScZc”,”Yy7VCbXVegM”,”h6kI9IdcvqQ”,”oMhvD2vTaSM”,”6z-Dh99GG7o”,”cniAs-R5uMM”,”_YTu4bFpKf8″);
    shuffle($testvids);
    foreach ($testvids as $testvid) {
    echo ‘[youtube]‘.$testvid.’[/youtube]‘ ;
    }
    [/php]

    does not work, with debug=1 I see echo “”. The entire echo line is stripped out.

    Tried the escape method

    echo ‘\[youtube\]‘.$testvide.’\[/youtube\]‘ ;

    in debug, the echo line is = echo “\”.$testvid.”\” ;

    and the output is = \oMhvD2vTaSM\\h6kI9IdcvqQ\\6z-Dh99GG7o\\FtyU7UXScZc\\_YTu4bFpKf8\\3f9QkEalfY8\\Yy7VCbXVegM\\cniAs-R5uMM\

    trying it with only one esc \[youtube], casues a parsing error.

    and the do_shortcode method

    echo do_shortcode(‘[youtube]‘.$testvide.’[/youtube]‘) ;

    Produces no result and an echo line = echo do_shortcode(“”) ;

    I have tried multiple variants of both, all with no luck… This simple php task has become a trouble-some bear.

    Running out of ideas, time and patience and hope you can assist.

    • Somehow I ended up on another page, and found the solution, use the [php useadvancedfilter]

      Maybe you would consider putting this in the wordpress Plugin Details … save other’s like myself lots of time and grey hairs.

  169. I am trying to add a code snippet. In Snippet Title i enter “My first snippet”
    in Snippet Code i enter “echo “Hello World”; and i get the error . Oh dear, could not add the code snippet . Why is this?

  170. Well, I updated to 3.0 today and it pretty much f***ed my whole site. My old code no-longer works. Thanks.

    • Hi Brandon

      What exactly is the issue, can you be more specific, what version did you upgrade from?

      Thanks,
      Jamie

      • I upgraded from 2.3 to 3.0. I had a simple php script in-between two typical [php] [/php] tags and it was no longer parsing. In fact, no content was parsing. The script locked my whole page up and none of its content would display. This includes content outside of the tags. It doesn’t make any sense. I have sense deleted the plug-in, re downloaded 2.3 and all is back to normal.

        • Hi Brandon,

          Without knowing the script I cannot advise you any further, feel free to email it to me at jamie.fraser@hitreach.co.uk

          It may be worth changing the code on the page to be a code snippet, once upgraded, that way you can use it on multiple pages across your site, and be able to update all of the scripts in one place (plus its nicer for editing!)

          Thanks,
          Jamie

        • Hi Brandon,

          After further looking into the issue, if you code is written in using the tag replacement, e.g. <a> is written like [a], then the updated version of the plugin automatically turns on the advanced filter method in the options.

          Try changing the [php] tags on the broken page to [php useadvancedfilter]…[/php useadvancedfilter] if that breaks your page, then it means your code is not compatible with the filter, so when upgrading, you would need to turn the advanced filter option off, or update the code to correct PHP syntax.

          thanks
          Jamie

          • It was/is a very simple meta-data script to pull out a users name. In retrospect I should’ve just hard-coded this into a shortcode for easy access, and that is what I have done now. However, the plug-in still shouldn’t be breaking from such a simple script:

            [php]
            $user_info = get_userdata(1);
            $username = $user_info->user_login;
            $first_name = $user_info->first_name;
            $last_name = $user_info->last_name;
            echo “Welcome back $first_name $last_name!”;
            [/php]

            I appreciate all of your time an efforts!

            • Hi Brandon,

              Its because of the &gt; in the $user_info-> , the advanced filter doesn’t have the intelligence to tell if the entity is to be encoded for note, so you need to provide it encoded!

              Turn off the advanced filter, or replace the &gt;s with >s and you should be fine :)

              thanks
              Jamie

  171. Hi, we spoke on the wordpress forum. The latest edition of your plugin appears to have broken the following code. Would be grateful for any help:

    [php]

    require(get_stylesheet_directory() . “/mypage.php”);
    [/php]

    Cheers :)

  172. I’ve use this php code in an text-widget in a sidebar:
    [php]
    require(ABSPATH . “/include/login_widget.php”);
    [/php]
    It did work fine before I updated to 2.3.
    What’s going wrong? Thanx!

    • I’ve solved it by turning off the advanced filter.
      Can somebody tell me what the advanced filter does and why I deeded to turn it off?
      Thanx.

  173. Dan Barnett says:

    Downloaded update and now my code won’t run in a sidebar “text/html” widget. [php function=3] just displays “[php function=3]” instead of running the function. Suggestions?

    Thank you.

    • Hi Dan,

      The plugin should apply a filter to the widget content to enable shortcodes to be used,

      check that there isn’t a conflict with another plugin removing the filter.

      Thanks
      Jamie

  174. Is there a way to add a variable on one post then include that variable on another post, for instance.

    PostA
    [php]
    $test=1;
    [/php]

    PostB

    [php]
    include(‘postA’); << How would I do this ?
    $echo $test
    [/php]

  175. On our privacy page, the icons are being listed vertically, everything works, it just likes to stand up…

    http://www.thehrisworld.com/verticals/about/privacy-policy/

    It is the same code that is being used on the Single.php file, which is working great (horizontal and all) – if there something I can use get these boys lined up properly? Or is this a theme issue?

    Thanks!
    Garrett

  176. Hi,

    My website depends on your plugin, but since the last update 3.0.1 I get an error
    Parse error: syntax error, unexpected ‘&’ in /home//public_html/cursus/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(420) : eval()’d code on line 4

    When I google on part of the phrase I get many many hits of pages showing the same error. Your assistance would be much appreciated, since I don’t have the previous version of the plugin saved. Thank you.

  177. PS: Found where to download version 2.3 and now my site works again. Still, a solution would be good, as it obviously isn’t my code that is faulted. I also tried setting the option back to ‘old’ version (not reccomended), but that didn’t help unfortunately. Thanks again.

    • Hi Jandra,

      The visual editor would have changed the & into its html entity &amp;

      The best way is to disable the advanced filter option, not the “old version” option.

      Thanks
      Jamie

      • Hi Jamie,

        Thank you for your prompt reply. Did I miss this info somewhere or perhaps is it worthwile to more clearly mention this in the plugin or upgrade info.

        Will future updates respect that setting or would I have to change it back every time? For the moment I think I’ll stay with version 2.3 unless there is an urgent reason for me to upgrade.

        Thanks again, Jandra

        • Hi Jandra,

          the setting for the advanced filter will be remembered across future updates and has been present since 2.3, it is probably worth while updating to 3.0.1. as the snippet update in 2.3 can sometimes fails to work.

          Thanks
          Jamie

  178. Hi,

    I had issues with the updated version of your plugin from ver 2.3 to Ver 3.0.1, it seems that the database prefix changed names from static $database_prefix = “allowPHP_functions”; to static $database_prefix = “allowphp_functions”;

    Which rendered my existing DB useless, and it would not allow any updates to the old database just got an error message ” Oh dear, could not add the code snippet”, I just changed the source code to the old lower case allowphp_functions and the plugin now works fine.

    Fix: on line 27 allowphp.php
    Old: static $database_prefix = “allowphp_functions”;
    New: static $database_prefix = “allowPHP_functions”;

    Or you could change the DB table name as suggested here:
    http://wordpress.org/support/topic/plugin-allow-php-in-posts-and-pages-plugin-broke

    • Hi Leslie,

      Thank you for your comment,

      The existing table upgrade should be renaming the table to the correct case anyway when you upgrade by doing calling the SQL:
      RENAME TABLE `".$wpdb->prefix."allowPHP_functions` TO `".$wpdb->prefix.self::$database_prefix."`
      during the DB upgrade.

      Thanks
      Jamie

      • Hi Jamie,

        I’m guessing that the database upgrade failed on my installation, could be due to my htaccess rules or security settings, to be honest I don’t remember running any db upgrade when upgrading the plugin (did it on Thursday only noticed issues on Tuesday).

        I guess several other users may have had the same issue as in the link I referred to in the post above, so at least one other person had the issue and am guessing several more from the comments above.

        BTW, good work on the new plugin, it certainly looks and feels way better.

        • Hi Leslie,

          it may be that you need to upgrade to the very latest 3.0.2 version to get the upgrade :)

          Thanks
          Jamie

          • Hi Jamie,
            I upgraded to 3.0.2 the DB upgrade still didn’t work, prob security settings, so I manually renamed the DB table to the correct new lower case.

            RENAME TABLE (wpprefix)allowPHP_functions TO (wpprefix)allowphp_functions

            Anyone with the same issue, just replace (wpprefix) in the SQL command above with your wp_prefix.

            Thanks,

            Leslie

  179. I don’t think that I made any changes to my blog (other than updating WordPress to 3.4.2) and now the referenced page shows some of the PHP code as text instead of running the actual PHP code. (But the PHP code in the sidebar works OK for some reason.)

    Any thoughts ? Thanks!

  180. Hi,
    I’m running WordPress 3.4.2 and Allow PHP Version 3.0.2

    On the homepage at http://www.thesurreyhipandkneeclinic.com before I upgraded to WordPress 3.4.2 I had a lovely section with Orthopedic news.

    Since I upgraded WordPress I now don’t get anything. I’ve set the debug to 1 and get the following error:
    Parse error: syntax error, unexpected T_NS_SEPARATOR, expecting ‘,’ or ‘;’ in /var/www/clients/client1/web3/web/wordpress/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 11

    Here’s the code that I’ve added to the page:
    [php debug=1]

    $feedURL = ‘http://www.medicalnewstoday.com/rss/bones-bone_disorders.xml’;
    // Load XML.
    $i=0;
    $rawXML = @file_get_contents($feedURL);
    $rss = simplexml_load_string($rawXML);
    foreach($rss->channel->item as $item){
    if($i>4){
    break;
    }
    echo”link.”\” target=\”_blank\” style=\”color:red;margin-bottom:0px\”>”.$item->title.””;
    $content = $item->children(‘http://purl.org/rss/1.0/modules/content/’);
    echo”[p]“.$item->description.”[/p]“;
    echo”[p]“.$item->pubDate.”[/p]“;
    $i++;

    }

    [/php]

    Any help is greatfully received…
    :o)

    • Sorry – the homepage with the news is at:

      http://www.thesurreyhipandkneeclinic.com/wordpress

    • Hi Ian,

      Try turning off the advanced filter to see if that helps.

      otherwise, try changing the &gt; to >s

      Thanks
      Jamie

      • OK the advanced filter is already switched off so I’m using [php][/php] to place the php directly on the page. With this method I get the following:

        Parse error: syntax error, unexpected T_NS_SEPARATOR, expecting ',' or ';' in /var/www/clients/client1/web3/web/wordpress/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()'d code on line 11

        Allow PHP Debug

        $feedURL = 'http://www.medicalnewstoday.com/rss/bones-bone_disorders.xml';
        // Load XML.
        $i=0;
        $rawXML = @file_get_contents($feedURL);
        $rss = simplexml_load_string($rawXML);
        foreach($rss->channel->item as $item){
        if($i>4){
        break;
        }
        echo"link."\" target=\"_blank\" style=\"color:red;margin-bottom:0px\">".$item->title."";
        $content = $item->children('http://purl.org/rss/1.0/modules/content/');
        echo"[p]".$item->description."";
        echo"[p]".$item->pubDate."";
        $i++;
        }

        End Allow PHP Debug

        ========> if you look above, the last couple of echo lines seem to end with a when displaying on the page.

  181. … continued (as your website thought I was a spammer)…

    If I enable advanced mode I get the following:

    [php debug=1]

    $feedURL = ‘http://www.medicalnewstoday.com/rss/bones-bone_disorders.xml’;
    // Load XML.
    $i=0;
    $rawXML = @file_get_contents($feedURL);
    $rss = simplexml_load_string($rawXML);
    foreach($rss->channel->item as $item){
    if($i>4){
    break;
    }
    echo”link.”\” target=\”_blank\” style=\”color:red;margin-bottom:0px\”>”.$item->title.””;
    $content = $item->children(‘http://purl.org/rss/1.0/modules/content/’);
    echo”[p]“.$item->description.”[/p]“;
    echo”[p]“.$item->pubDate.”[/p]“;
    $i++;

    }

    ?>

    ========> Note the opening [php debug=1] and the closing ?>

    I think there may be a bug?

    Best regards,
    Ian.

    • Hi Ian,

      I’m not sure if its the comment editor, or your code, but large sections are missing, i have altered it, and this version works fine:


      [php]
      $feedURL = 'http://www.medicalnewstoday.com/rss/bones-bone_disorders.xml';
      $i=0;
      $rawXML = @file_get_contents($feedURL);
      $rss = simplexml_load_string($rawXML);
      foreach($rss->channel->item as $item){
      if($i>4){
      break;
      }
      echo "<a href='$item->link'target='_blank' style='color:red;margin-bottom:0px'>".$item->title."</a>";
      $content = $item->children('http://purl.org/rss/1.0/modules/content/');
      echo "<p>".$item->description."</a>";
      echo "</p>".$item->pubDate."</p>";
      $i++;
      }
      [/php]

      Just add the above in place of the existing code in HTML mode, or better yet, add it as a snippet, then you can easily use it in more than one place.

      Thanks
      Jamie

  182. Hello,
    I’m using your plugin for several months now and i’ve just installed the Polylang plugin. As soon as i activate it, the php code isn’t interpreted anymore.
    Have you heard about some conflicts with others plugins like multilanguages ones?
    I really need your plugin and Polylang too i hope i’ll be able to use both.
    Any ideas?

    • Hi Nataly,

      There is no reported conflict issues with other plugins so far, it could be the translation plugin is causing issues with the php code in the post, try moving it to a code snippet and seeing if that works.

      thanks
      Jamie

      • Hi Jamie, thank you for replying.
        I’ve activated the debug mode and i think i found where is the problem.
        When i activate Polylang plugin, and switch to french, the ” is replaced by « which cause an error.
        Now i don’t know if this means that the fr_FR.mo file should be modified or the code of your plugin, in order to not replace the ” character.
        What do you think?

      • By the way you told me to try moving the code to a snippet but i’m not very good at using snippet i think, because it doesn’t work.
        I’m using global variables that are initialized in one part and used in another.
        Can global variables can be call from a snippet when they are initialized in another?

  183. I got rid of the problem : i’ve checked “Use the advanced filter method” in the options panel.
    If you have some time, i would be happy to understand what this option does and why it solves my problem.
    Thank you :0)

    • The advanced filter applies to the post content when it is read from the database, rather than on the do_shortcode hook, so it is likely that the translation plugin is getting the code after it has been executed by the filter, solving your problem :)

      thanks
      Jamie

  184. I used this code and it will not work using relative or absolute path. Why is that? From some of the previous posts by other people it seems like it would work.

    [php]include(“http://equityinfo.org/wp-content/themes/canvas/phpcontent/content-test.php”);[/php]

    Or

    [php]include(“/wp-content/themes/canvas/phpcontent/content-test.php”);[/php]

    Warning: include() [function.include]: URL file-access is disabled in the server configuration in /home/equityin/public_html/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 1

    Warning: include(http://equityinfo.org/wp-content/themes/canvas/phpcontent/content-test.php) [function.include]: failed to open stream: no suitable wrapper could be found in /home/equityin/public_html/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 1

  185. Getting the following error:
    Invalid argument supplied for foreach() in C:\inetpub\vhosts\1car1difference.com\misixdev4\wp-content\plugins\allow-php-in-posts-and-pages\allowphp.php(373) : eval()’d code on line

    using the following code
    [php]
    foreach ($stateArr as $key=>$val) {
    echo ”.$val.”;
    }
    [/php]

    any help would be appreciated. I’m a wordpress newbie and the above works on my regular page.

    thanks!

    • ok, got it to work, had to change the bracketing, now is there any way I can define my $stateARR in a separate php file and still get that value here?

      • Hi Nathan,

        You can set $stateARR as a global variable in your separate file and get the value by referencing the global variable, or you could include the file using php include.

        Thanks
        Jamie

  186. I’ve been at this include thing now for 2 hours and can’t get it to work!! I’ve tried every possible answer stated here and then some… But I end up with nothing!

    This is the path to the file I want to include:
    http://mysite.com/wp-content/themes/mytheme/includes/latest.php
    (Can access this file directly and other php functions such as echo works on page)

    Can someone Pleeeease give me the code to put on my page. (Version 3.0.2)

    • Hi Chrille,

      It could be that the URL include is not allowed by your hosting, Try including using the realpath on the server (e.g. /home/usr/public_html/….. ) to get the real path try the following code:

      $path = realpath(".");
      $path .= "/wp-content/themes/mytheme/includes/latest.php";
      include($path);
      

      Thanks
      Jamie

  187. Sandy Doss says:

    Hello, and thank you! The Allow PHP on Posts and Pages plugin turned out to be exactly what we needed in a ‘melded’ website of WordPress pages and home-grown cgi pages. Had to experiment a bit with it, but finally achieved the goal of building links on the fly inside of a page with the help of the plugin. So thanks again for making my life easier!

    One thing of note – and I don’t know if it is your plugin, WordPress 3.0.5, or a combination of – but when using the editor, on a page where we’d uploaded images (to act as links), after placing the [php]…[/php] shortcodes, when we flipped from the html editor to the visual, then back to the html – our html had disappeared! I tried it several times – without the shortcodes, the html remained; with the shortcodes – it disappeared – just an fyi.

  188. Hi Jamie,

    Love the allow php and javascript plugins along with purehtml. They work great for me with everything I have tried.

    Only one snag so far, have recently upgraded Allow php in posts and pages from 2.03 to 3.02

    Now getting the following syntax error

    Parse error: syntax error, unexpected ‘<' in /usr/local/pem/vhosts/106226/webspace/httpdocs/coralbaywa/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()'d code on line 6

    Seems like it should be an easy fix but with knowing less php than my pet goldfish I am hoping for some help.

    Code below worked with 2.03

    [php debug=1 useadvancedfilter] $select = wp_dropdown_pages(‘&child_of=15&show_option_none=Please%20select%20an%20accommodation%20type&depth=1&sort_column=menu_order&echo=0′);
    $select = preg_replace(“#]*)>#”, “”, $select);
    echo $select;
    [/php useadvancedfilter]

    Thanks in advance

    • Hi Tony,

      I have checked your code and the issue appears in your regex used for the preg_replace,

      You need to escape the * and the ) for it to work correctly.

      I had it working with:

      [php useadvancedfilter] 
      $select = wp_dropdown_pages('&child_of=15&show_option_none=Please%20select%20an%20accommodation%20type&depth=1&sort_column=menu_order&echo=0');
      $select = preg_replace("#]\*\)\>#", "", $select);
      echo $select;
      [/php useadvancedfilter]
      

      Thanks
      Jamie

  189. Sorry this question is so basic, but I’m unable to generate a simple html table on Pages using [php]. Can you please explain why?

    This code fails:

    [php]
    echo “[table border="1"]“;
    echo “[tr]“;
    echo “[td]row 1, cell 1[/td]“;
    echo “[td]row 1, cell 2[/td]“;
    echo “[/tr]“;
    echo “[tr]“;
    echo “[td]row 2, cell 1[/td]“;
    echo “[td]row 2, cell 2[/td]“;
    echo “[/tr]“;
    echo “[/table]“;
    [/php]

  190. I haven a little trouble making my code work with you plugin. I am sure its something small I doing but can some one please help.

    Code:

    Support Controls

    Control
    Control

    <?php for($i = 0; $i

    I know that the php tags need to be changed but I still have some trouble with it given me errors

    Code I try to use
    [php]

    $controls = array(‘a’, ‘b’, ‘d’, ‘c’, ‘e’);
    sort($controls);
    $size = sizeof($controls);

    [/php]

    Support Controls

    Control
    Control

    [php] for($i = 0; $i < $size / 2; $i++ ) [/php]

    [php]= $controls[$i]?>
    [php]= $controls[$i + ceil($size / 2)][/php]

    [php] [/php]

    Error I get
    Parse error: syntax error, unexpected $end in /home/content/88/9434388/html/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 1
    Control

    Control

    Parse error: syntax error, unexpected ‘=’ in /home/content/88/9434388/html/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 1

    Thank you for you time

  191. Ronald Wong says:

    Jamie:
    i’ve started learning php for few day.But i don’t know why i can’t even use the wile loop in your plugin.How can i solve it?
    [php]
    $i=0;
    $x=5;
    while($i<=$x){
    echo "hello world";
    $i=$i+1;
    }
    [/php]
    error received
    Parse error: syntax error, unexpected $end in S:\Ronald\ict sba\wordpress\xampp\htdocs\wordpress\wp-content\plugins\allow-php-in-posts-and-pages\allowphp.php(373) : eval()'d code on line 4
    by using debug,the output is:
    Allow PHP Debug

    $i=0;
    $x=5;
    while($i
    End Allow PHP Debug

  192. I have been using your plugin for a few months and love it, however, I just upgraded my WordPress site to version 3.5 and am now getting the following error on the settings page for the plugin (masking characters added for security reasons):

    Warning: Missing argument 2 for wpdb::prepare(), called in /####/######/#######/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php on line 182 and defined in /home/comple59/vppstore.com/wp-includes/wp-db.php on line 990

    I am not sure how to correct the issue myself, so I was wondering if you had any ideas that I might be able to try.

    Thanks

    • Hi Chris

      The plugin still needs to be reviewed for compatibility with WordPress 3.5, it is likely that when we do the compatibility review we will also fix your problem,

      In the mean time, if you open the allowphp file in a text editor and locate the function:

      function snippet_get_all( ){
      	global $wpdb;
      	$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `".$wpdb->prefix.self::$database_prefix."`") );	
      	return $rows;
      }
      

      and replace it with:

      function snippet_get_all( ){
      	global $wpdb;
      	$rows = $wpdb->get_results( ( "SELECT * FROM `".$wpdb->prefix.self::$database_prefix."`") );	
      	return $rows;
      }
      

      This should fix your problem.

      thanks
      Jamie

  193. Hi !

    I’m having various bloody eval(encode64) attacks,
    I still did not find the cause.

    Do you think it COULD be your plugin used by some other malicious plugin/script ?

  194. Ok, I will contact you, but I’m not accusing you of course,
    infact the problem was probably caused by an old and unsafe TimThumb script.

    bye !

  195. When I use the more tag after the php code the code is not run, instead i get the raw code.
    Here is the code i use http://pastebin.com/7SXJbf6e , without the more tag it is working.

    With the more tag.
    http://i.imgur.com/32rGR.jpg
    Without the more tag.
    http://i.imgur.com/d0LlC.jpg

  196. I’m looking for some sample code for [php function=x] to display URL parameters like http://helpingstudents.morten.me/?page_id=249&myvalue=23
    So I can echo “23″ to the page.
    Also I would love to be able to pass some text including spaces.
    Any help is greately appreciates. Also thanks to Christ Gilchrist for great chat service..

  197. Love this plugin, specially the new feature so that we get rid of the shortcode tags ([php] … [/php] so that we can now use normal Opening & Closing PHP Tags! :)

    Any possibility to donate some money?

    Thanks! ;)

  198. Hi,

    I’m trying to use a shortcode from another plugin but I can’t get it to work.

    Here is the code that I’m using;

    echo do_shortcode(‘[contact-form 1 \"Contact Us\"]‘);

    Turning the debug on is generating this;

    echo do_shortcode(”);

    How should be coding this?

    BTW, great plugin!

    Marcelo

    • Sorry, it seems like the code generated was cut out. My whole original comment as it should have been is;

      I’m trying to use a shortcode from another plugin but I can’t get it to work.
      Here is the code that I’m using;
      echo do_shortcode(‘\[contact-form 1 \"Contact Us\"\]‘);
      Turning the debug on is generating this, (I’ve put everything in “” so it doesn’t get dropped … hope this works!);
      “echo do_shortcode(‘\’);”
      How should be coding this?
      BTW, great plugin!
      Marcelo

    • Hi Marcelo,

      Turn the call into a code snippet, it works better than in-line embedding for this purpose where the output isn’t simply a single variable.

      For you code it is like the [ is being changed to < which isn't a shortcode tag, you could try escaping the square bracket so its \[contact-form 1 \"contact Us\"\] and seeing if that helps

      Thanks
      Jamie

  199. I am also running into problems with doing a php include in a post using this plugin. From what I’ve read here I feel like the following should work:

    [php]include(“http://www.punchdrunkwonderland.com/ads/pdw-google-336×280.php”);[/php]

    I’m also using a PHP Code Widget that allows me to use php code in my widgets. I’m using these to include ad code from an ad directory in order to have greater control over bots via the robots.txt file. The widgets are working fine, but this plugin appears to not be working for me in posts. Thoughts?

  200. In terms of security, is there a way to block php for posts but allow them for pages?

    • Hi Allen,

      The plugin utilizes shortcodes and filters, natively within the code there is not a way to disable it, but within your themes function file you can make use of the !is_page() if statement to remove the filters and shortcodes.

      Thanks
      Jamie

  201. I’m not sure if this was addressed elsewhere (I’ve searched the comments for keywords that might point it out), but I’m trying to use this plugin to add an application to our WordPress site that uses the include_once function. I’ve made each of these lines its own snippet, so I can call it when needed from within the page. At the moment, however, it appears to be displaying the called PHP code as text. Any advice you can provide would be appreciated.

    • Hi Matt,

      For clarity, can you tell me which code is displaying as text, the include(“file”); or the file contents?

      thanks
      Jamie

      • I’d be glad to! But would it be possible to contact you via email or an unmoderated comment, rather than posting a link to publicly displayed PHP code? Much obliged!

      • To clarify in the meantime as you requested, it’s the contents of the included file that are displaying as text on the page. Sorry, misread!

        • Hi Matt,

          Try starting the php include file with <?php and see if that works.

          Thanks,
          Jamie

          • I’m afraid that gives me a “Parse error: syntax error, unexpected ‘<'" error message.

          • I’m also in the process of converting the appropriate HTML tags to BB Code, so we can hit the ground running once this issue is resolved. This is, I’m afraid, a time-sensitive project.

            Do I need to do anything to the code in the WordPress page that contains the code snippet references? These appear within the broad [php] tag, for example, but I’ve tried closing and reopening that tag around the snippets, with no success.

            • Hi Matt,

              what happens if you make the code into a snippet and embed it that way? using the [php function=x] shortcode.

              Thanks,
              Jamie

              • Good question! I’ll do so and get back to you. Thanks!

              • Right, I’ve copied the full code from all of the included files into their own snippets, and I’ve tried the embed that way. I’m still getting an “unexpected ‘<'" syntax error when I load the page, on the line where the first of those included files is called with a snippet. Which is odd, because there's no '<' anywhere in the snippet.

                I also tried a closing [/php] tag in the main file, right before calling the first snippet. This returns a WordPress page with no body content.

              • hmm, threaded comment limit,

                Anyway, I think you may have missed the point, I meant to solely turn the php which includes the file into a snippet, not all the files :)

                Thanks,
                Jamie

  202. Hi,

    When we updated our PHP to version 5.4 we got this warning on each of our pages that have PHP on them.”illegal string offset ‘debug’” in the allowphp.php page. We are currently using WordPress 3.2.1 and Allow PHP in Posts 2.1.05. Do you have a fix for this problem?

    Thanks for creating this plugin!!

    Matthew Hoffland

    • Hi Matthew,

      We don’t keep that version of the plugin on file any more.

      Please can you email it to me and I will make the necessary fixes and return it to you.

      Thanks,
      Jamie

  203. I want to use this plugin in order to check if a variable is true then show me a message at 12pt size else show me the same message at default size. Here is my example :

    [php]
    if ($checkMobile == 1) {
    echo “[span style="font-size: 12px;"] This is my [strong]True Message[/strong].[/span]“;
    }
    else {
    echo “This is my [strong]False Message[/strong].”;
    }
    [/php]

    I write the above example and didnt work for me. I think that your plugin didnt recognize styles…

    Can you give me a solution ?

    Thank you in advance :)

  204. [PHP]

    session_start();

    require_once(‘./wp-content/plugins/wp-modal-login/connect.php’);

    if(!isset($_SESSION['email']))

    {

    $_SESSION['msg'] = “Please Login First !”;
    header(‘location:http://localhost/wordpress/?page_id=103‘);
    exit();

    }

    $login_email = $_SESSION['email'];

    $data=”SELECT * FROM userlogin WHERE email=’$login_email’”;
    $rec=mysql_query($data);
    $record=mysql_fetch_array($rec);
    echo ”

    “;
    echo “Welcome Back, “.$record['name'];
    echo ”

    “;
    $exp = explode(“,”,$record['cat']);
    foreach($exp as $key)
    {
    if($key==’1′)
    {
    echo ‘video mp4=”./video/akk1.mp4″‘;
    }
    if($key==’2′)
    {
    echo “hello1″;
    }
    if($key==’3′)
    {
    echo “hello2″;
    }

    }
    [/PHP]

    i have a player shortcode [video mp4='./akk.mp4']. can anyone tell me how can i add this shortcode into the if statement. thankyou in advance

    • Hi Amit,

      You will need to use the do_shortcode function, and square brackets can be written as \[ and \].

      Alternatively using the advanced filter or code snippets should avoid you having to escape the square brackets.

      Thanks,
      Jamie

  205. hi – Sorry – please delete my last 2 comments. after reading through all of these posts i have finally settled on:

    [php]
    if(is_user_logged_in()){
    echo “[h4]Members[/h4]“;
    echo do_shortcode(‘/[show-menu menu="Members"/]‘);
    }
    [/php]

    in order to get my [show-menu menu="Members"] shortcode working – but all i get is a /

    i have tried a range of variances but just cannot seem to get it. i would really appreciate your feedback as im sure its probably a syntax error.

    thanks.

    • all good – i finally got it.
      i turned on ‘Use the advanced filter method’
      and used the following:
      [php]
      if(is_user_logged_in()){
      echo do_shortcode(‘[show-menu menu="Members"]‘);
      }
      [/php]
      great plugin!!

  206. Hello,

    Can it be used to call another php file ?
    to do something like

    Because the more i try, the more i receive a error message.

    Could it be because of the new WP version is not compatible ?

    tanxs

    • grant@HitReach says:

      Hi Nick, it should be possible to include another php file. The only thing to watch out for is that you may need to write the path to the include from the root of your WordPress installation. e.g.
      [php]
      include(‘wp-content/themes/twentytwelve/hello.php’);
      [/php]

  207. Daryl Lim says:

    Can’t seem to get the include() function to work with the snippet.

    Here is my code:

    include(get_stylesheet_directory_uri() . ‘/live-gallery.php’);

    This does not display anything when it should. I understand from previous comments that I should specify an absolute path. But, since this file is situated in the root directory, I have also tried:

    include(‘live-gallery.php’);

    …which also does not work. Is this some known issue with the include() function?

    • grant@HitReach says:

      Hi Daryl,

      I believe you would have been having problems because of your use of get_stylesheet_directory_uri() which will return a url with http:// at the start. Try using get_stylesheet_directory() instead

  208. HI there,

    Parse error: syntax error, unexpected ‘<' in /home/rschmitz/public_html/wordpress/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(839) : eval()’d code on line 2

    I'm getting this error and I am at a loss to see the problem, I need this to work for an assessment at tafe.

    Rick

    • grant@HitReach says:

      Hi Richard, It looks there was a missing underscore that was messing things up a little. I have just released the 3.0.4 version which should fix your problems. Thanks, Grant

  209. Fernando says:

    How can I disable comments on a page that is using php code. I am not able to do it. Any clues?

    Thank you!

  210. hi i have this code in widget
    Please submit the options to find a trip of your interest:
    Country:
    Nepal
    Tibet
    Bhutan
    Nepal and Tibet
    Nepal and Bhutan
    Nepal, Tibet, and Bhutan

    and in my trip-finder i just simply put
    [php]
    echo “You want a Tour in Nepal for 3 nights. Please find the Trip/s you are looking for:”;
    [/php]
    but it displays
    Parse error: syntax error, unexpected ‘}’ in C:\xampp\htdocs\wordpress\wp-content\plugins\allow-php-in-posts-and-pages\allowphp.php(373) : eval()’d code on line 3

    what is the problem??? pls advise.

    • grant@HitReach says:

      Hi Sabin,

      I couldn’t get your code to cause an error. Please try updating to the newest version of the plugin and see if that helps.

  211. Fernando says:

    Can you please tell me what is the proper way to write this

    [php]
    // The Query
    $the_query = new WP_Query( ‘cat=4&posts_per_page=-1′ );
    // The Loop
    while ( $the_query->have_posts() ) :
    $the_query->the_post();
    echo ‘‘.get_the_title().’‘;
    endwhile;
    /* Restore original Post Data
    * NB: Because we are using new WP_Query we aren’t stomping on the
    * original $wp_query and it does not need to be reset.
    */
    wp_reset_postdata();
    [/php]

    The & in wp_query is getting converted to &

    Thank you!

    • grant@HitReach says:

      Hi Fernando,

      You could try using the get_posts function instead:

      [php]
      $args = array(
      'posts_per_page' => -1,
      'offset' => 0,
      'category' => '4',
      'orderby' => 'post_date',
      'order' => 'DESC',
      'post_status' => 'publish');

      $posts = get_posts($args);

      foreach ($posts as $post) : setup_postdata($post);
      the_title();
      endforeach;

      wp_reset_postdata();
      [/php]

  212. Can I embed a code snippet in a post, and pass a variable to it? I have a snippet I want to use on every page of my site, but it has one variable that needs changing each time (if you happen to see this soon and have an answer for me, I need to get this done today, but I understand if you don’t get to it). Thanks!

    • grant@HitReach says:

      Hi Phil, unfortunately that is not built into the plugin. Would be interested to hear what approach you ended up taking. I would probably recommend trying to detect the current url in the function and basing it off of that

      • I have a membership site with 450+ videos embedded from Vimeo. I wanted to have the embed code in 1 place in case it ever changes. Anyway, I ended up posting this on every wordpress post, and then just manually changing the vid:

        [php]global $allow_php; $allow_php->_shared['vid']=’86064446′;[/php][php function=1][/php]

    • help4phil says:

      Hi Phil,

      Create a snippet in the code snippets with your function and include it on the pages you want.

      then just before you include it, create an inline function that sets the Allow PHP’s shared variables ($allow_php->_shared["key"] => “val”)

      you will now be able to pass variables from inline scripts to code snippets

      Hope it helps.

  213. I am running into troubles using php classes.

    I defined a simple class then tried to create it.
    I tried both pasting all the code into a snippet and also calling it from an include file so just calling the include file in the snippet.

    The definition of the class (class ClassName{…) is on line 6. Here is the error I get:

    Fatal error: Cannot redeclare class WedB_OrderForm in /home/sitename/public_html/wp-content/app_includes/details.php on line 8

    Thanks!

    • grant@HitReach says:

      Hi Allon, there shouldn’t be any problems with running classes. Have you tried putting your class inside if(!class_exists(class_name)) {} so you don’t end up with duplicate classes?

  214. Bob Anderson says:

    Is there a way to pass variables between pages using this plugin? Thanks!

  215. Bob Anderson says:

    I ended up not being able to use this plugin. Instead I found a plugin that turned on sessions in WordPress and did the php coding in template files for the pages. Thanks

  216. Unfortunately, nothing worked for me, even if i was testing sometings very simple…
    I tried :
    [allowphp debug=1]
    echo “test”
    [/allowphp]
    then with [php] and [/php], then I remove debug=1, then i tried using an include (‘test.php’); but still did not work :/
    I got always the same message error : Parse error: syntax error, unexpected ‘&’ in filepath\allow-php-in-posts-and-pages\allowphp.php(373) : eval()’d code on line 2
    And the debug : echo « test »;
    Can’t understand why, i’m not using any & or  
    :(

    • grant@HitReach says:

      Hi Lea, Are you definitely running the latest version of the plugin? There was a bug in a previous version which may have caused this problem.

  217. I’m using wp 3.5.2 and ur latest 3.0.4. And it is not working at all.
    I am using a custom template which i think may be the route of the problem. The template DOES use
    So I’m not understanding why plugin doesn’t work in content OR in the WP html widget.

    In a post I use these 3 to test:
    [php]php echo get_post_meta($post->ID, ‘post_title’)[/php]
    [php]php the_meta(); [/php]
    [php function=2]

    For those 3 attempts, I get:
    Parse error: syntax error, unexpected T_ECHO in /home/site/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 1

    Parse error: syntax error, unexpected T_STRING in /home/site/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 1

    Parse error: syntax error, unexpected ‘<' in /home/site/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()'d code on line 1

    • grant@HitReach says:

      Hi Bernard,

      I don’t know the comments have modified your code but [php]php echo... won’t work but if you take out the extra php it should start working: [php]echo... you will also have to set the global post variable before you can use $post

      [php]
      global $post;
      echo get_post_meta($post->ID, 'post_title', true);
      [/php]

  218. incompitance kills says:

    Its because the code editor in wp is replacing your quote marks with ‘smart ones’ causing your code to break. Use snippets instead.

  219. Bernard Berry says:

    Can you PLEASE tell me how to get Allow Php working in sidebar widgets, or does it simply not work.

    I already have add_filter(‘widget_text’, ‘do_shortcode’);
    in funtions.php

    Using just the simplest of php, echo and that doesn’t work.

    I used:
    [php useadvancedfilter]the_field(‘nickname’, ‘user_2′);[/php useadvancedfilter]

    [php]
    global $user_ID;
    if($user_ID == 1){
    echo “Hello World”;
    }
    [/php]

    [php]global $wp_query;
    $postid = $wp_query->post->ID;
    echo get_post_meta($postid, ‘model_booking_email’, true);
    wp_reset_query();[/php]

    All of the above work in post and pages, but not in widget right there on the same post/page.

    I’ve used the above in a reg txt widget AND in a widget that allows shortcodes specifically.

    What is the fix?

    • grant@HitReach says:

      Hi Bernard, I’m afraid the plugin is not set up to work in widgets at the moment. May be something worth looking into in the future though.

  220. Being new to PHP I have a rather simple question that is bugging me. I am trying to run code stored in your addon (i.e. [php function=1]) by clicking a submit button. My problem is in the html syntax since I am not calling a .php file.

    So if my php snippit begins with: if(isset($_POST['submit'])) {

    and my html code is:
    [php function=1]

    how do I need to modify this to make the php code execute when the submit button is clicked? Thanks!

    • grant@HitReach says:

      Hi there, there’s no real way to run PHP on clicking a button, there needs to be a refresh or a new page setting used somewhere. If you try making the html a form with action="" method="post" then the form will submit to the same page and hopefully your snippet will run.

  221. Hi,
    I am trying to do the following:

    [php]
    for($i=0;$i<31;$i++)
    {
    echo '’.$i.”;
    }
    [/php]

    But nothing s being displayed in the dropdown

    • grant@HitReach says:

      Hi Ritika,

      It looks like it is having a problem with the spacing of your code for some reason. This worked for me:
      for ($i=0; $i < 31; $i++) {
      echo $i;
      }

  222. hi
    i want to declare a class, for example a student class

    class student{
    function hello(){
    return ‘hello’
    }
    }
    i want to create a new object from this class in one of the pages
    $s=new Student;
    echo $s->hello();

    how can i do that?
    can i use my own written classes in wordpress in this way?
    where should i create these classes?

    • grant@HitReach says:

      Hi there,

      If you include the class in your functions file then it will be available in all your templates as well as directly through the plugin.

  223. Hi,

    WordPress version 3.6
    Plugin version 3.0.4

    I’m trying to make something really simple work, but not getting anywhere, so I hope you can tell me what’s going wrong.

    I have tried using both [php useadvancedfilter] and [allowphp useadvancedfilter] and they just display all of the PHP code. Removing useadvancedfilter seems to execute the code, at least it’s not spit out to the page, but nothing comes back from the echo statements.

    Here’s an example of the code I’m trying to use:

    [allowphp]

    if($_POST['which'] == “page1″) {
    echo ”;
    } else {
    echo ”;
    }

    [/allowphp]

    • grant@HitReach says:

      Hi Robert,

      Unfortunately I could not replicate the error you have been getting also running the same versions. The code below worked fine for me:




      [allowphp]

      if($_POST['which'] == 'page1') {
      echo '1';
      } else {
      echo '2';
      }

      [/allowphp]

  224. Sorry, it looks like the editor stripped out the code inside my echo statements.

    Anyway, those should be two different iframe statements being echoed depending on the input from $_POST.

    How can I get the echo to work?

    • grant@HitReach says:

      Hi Robert,

      Yeah I only got some of the code from your previous comment but it looked like you were outputting some of the html for the iframe inside [php] tags and some outside. I would recommend doing it all inside the [php] tags, that way wordpress wont interfere by adding paragraphs and line breaks

  225. Hi, Thanks for this great Plugin!
    I have a question…
    How to use on page included other snippet for other plugin, example:

    I used other plugin called “Profile Builder”, and this plugin have tag:

    [wppb-edit-profile]

    This tag show user profile info…
    how to use this tag inside page included?

    e.g, i Have a snippet:

    include(TEMPLATEPATH . ‘/userconfig.php’); ?>

    and inside page “userconfig.php”,I would include the tag [wppb-edit-profile], but this tag dont work with include, function it does not work, it only shows the tag in text format, how can I fix it?

    Best Regards.

  226. Jeremie Calvin says:

    Thank you so much for this email. I know with you help I can get it working perfectly. I used to have this code in my template.

    ID, price, true);
    $b = 199;
    $c = 1000;

    echo(“18K Gold – $” . ($a + $b) . “.00″);
    echo(“Palladium – $” . ($a + $b) . “.00″);
    echo(“Platinum – $” . ($a + $c) . “.00″);
    ?>

    It worked perfectly. However I now need to get rid of the template code and actually put it in the post by itself. This is what it looks like now.

    [php]
    $a = get_post_meta($post->ID, price, true);
    $b = 199;
    $c = 1000;

    echo(“18K Gold – $” . ($a + $b) . “.00[br/]“);
    echo(“Palladium – $” . ($a + $b) . “.00[br/]“);
    echo(“Platinum – $” . ($a + $c) . “.00″);
    [/php]

    The only thing that shows up is the $b and $c without the adding process. It renders this.

    18K Gold – $199.00
    Palladium – $199.00
    Platinum – $1000.00.

    I’m an absolute newbie on PHP, and only know what I look up. Can you tell me what I would need to change to make this work?

    Thanks.
    Jeremie

    • grant@HitReach says:

      Hi Jeremie, If the code is actually going into the post itself then I would recommend just using the the actual ID for getting the meta eg get_post_meta(32, price, true);

      Hope that helps.

  227. snippets works well but there is something badly wrong when a mix of inline php code and snippets are used.

    [code]
    [php function=3]
    my first text
    [php debug=0] echo 'this is test 01'; [/php]

    my second text
    [php debug=0] echo 'this is test 02'; [/php]
    [/code]

    the result is

    “test

    my second text
    this is test 02″

    php function 3 is just another echo “test”

    the section
    [code] my first text
    [php debug=0] echo 'this is test 01'; [/code] is completely dropped and enabling debug info does not show any error either

    • Hi Nishan,

      In my tests this seemed to work fine with the debugs removed. Maybe double check your php in the snippet?


      [php function=1]
      my first text
      [php] echo 'this is test 01'; [/php]

      my second text
      [php] echo 'this is test 02'; [/php]

  228. Thanks for creating this wonderful plugin. I have some bitcoin to donate.

    My table is created, but ugly.
    Any thoughts appreciated!
    -cellurl
    ——————————-

    [php debug=1]
    include(“../dbconnectlocal.php”);

    $query = “SELECT name,sum(num_submits) as num_submits FROM summary group by name”;

    $result = mysql_query($query);

    echo “\n”;
    echo “\n”;
    echo ” Name\n”;
    echo ” Num Submits\n”;
    echo “\n”;

    while($row = mysql_fetch_array($result))
    {
    echo “\n”;
    echo “” . $row['name'] . “\n”;
    echo “” . $row['num_submits'] . “\n”;
    echo “\n”;
    }

    echo “\n”;
    echo “\n”;
    [/php]

  229. I got it,
    Just replace with ]

    Thanks guys!
    Sweet

  230. holy crap batman.

    just replace left angle bracket with left square bracket.

    and replace right angle bracket with right square bracket.

    DO IT EVERYWHERE… It works.

  231. I’m a novice at php but have code that is working non-WP site that I’d like to adapt to this WP site.

    It simply receives a variable called id which is a number and that sets one of the audio files to “autoplay” by setting the attribute to true.

    I’ve installed the plugin but don’t know how to send that page a ?id=1 variable and get the
    [php]if ($id==’1′) echo “autoPlay=’true’”;[/php]
    to fire.

    Lots of great comments and kudos for the work you’ve done for so many with this plugin.
    ~nicholas

    • Grant Richmond says:

      Hi Nicholas,

      I think what you’re looking for is

      [php]if ($_GET['id']=="1") echo "autoPlay='true'";[/php]

      I would also recommend using something more unique than id as you may have problems with built in WordPress functionality.

  232. It breaks when I try to use “less-than” signs or “more-than” signs. I want to write:
    if ($variable more-than 5)
    but it doesn’t work. Replacing the more-than sign with a bracket doesn’t help. Any ideas?

  233. I solved it by using their “entity names”: > for “more than”, and < for “less than”. Like this:
    if ($variable >5)

  234. argh… the “entity names” disappeared when I posted. just google “html entities” and you find it.

  235. Hi,

    WordPress 3.3.1.
    Plug In Version 2.2.0

    I’ve been tampering with the HTML in the Header.php Template (Appearance -> Editor) in order to add an Instagram emblem to the home page header.

    Unfortunately, the problem I seem to keep bumping into is trying to import the same stylized (the circular-shaped) social media emblem into the header.

    Any suggestions would help greatly and would be appreciated :)

  236. I have one page thats showing this after I updated some plug-ins, is there a problem with the plug-in
    Catchable fatal error: Object of class WP_User could not be converted to string in /home/auctions/public_html/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 1

  237. It dosnt seem to support curl, it works fine up to the point of curl? any ideas?
    http://wordpress.stackexchange.com/questions/116834/why-is-curl-not-working-in-wordpress-page-using-php-plugin

    • Grant Richmond says:

      Hi Scott,

      I’m pretty sure this is because headers will have already been sent out by WordPress by the time it gets around to executing the Allow PHP code. I would recommend integrating this functionality into a plugin or theme and using an add_action( 'init' ... hook and the code should get run before anything gets output.

      Hope that helps,
      Grant

  238. Hi, first of all, your plugin is wonderfull but who knows using :)

    i add a table to db like wp_mapmus

    and i want to show with your plugin.

    i use

    $sonuc = $db->get_row(“SELECT name, point
    FROM $wpdb->mapmus WHERE id=1″);
    echo $sonuc->name;
    echo $sonuc->point;

    but its wrong, how can i show some information. ?

  239. Jim Kristiansson says:

    Hi, im cant get your plugin to work. I am using a custom buildt gusetbook that has worked fine for me earlier. I get this error:

    Parse error: syntax error, unexpected end of file, expecting ‘,’ or ‘;’ in /storage/content/00/164100/jkweb.se/public_html/G360/wp-content/plugins/allow-php-in-posts-and-pages/allowphp.php(373) : eval()’d code on line 1

    Here is the code i have om my page:

    Best regards
    Jim

    • Grant Richmond says:

      Hi Jim,

      Unfortunately I couldn’t see anything in particular wrong with your code, I would maybe try and reduce the number of quote marks, I don’t thing there all necessary everywhere. Also make sure not to post your database login details anywhere, it’s not a good idea.

      Thanks,
      Grant

  240. Hello,
    I have downloaded and activated this plugin but when I enter the shortcode into my wordpress page for example [allowphp function=3] or [php function=3] it does not show anything on the page. When I click on “Use advanced filter method” under general options then all I see is the short code on the page. What can possibly be the problem? Thank you.

    • Hi Nathan,

      I’ve not been able to replicate your problem. Can you make sure you have a snippet with the ID of 3 and that there are no errors in it.

      Thanks,
      Grant

  241. I have this code which is not working, can anyone make it correct

    Name
    POS
    RAT
    SHO
    PAS
    DRI
    DEF
    HEA
    SKI
    WFT

    [php]

    $show = mysql_query(‘Select * from gallery_d order by gdorder’) or die(mysql_error());
    $records = mysql_num_rows($show);
    if($records > 0)
    {
    $i = 1;
    $gdshow= array(’1′=>’Active’,’0′=>’Inactive’);
    while($row = mysql_fetch_assoc($show))
    {
    if($i%2==0)
    {
    $bgcolor = ‘#f0f0f0′;
    }
    else
    {
    $bgcolor = ‘#fafafa’;
    }

    [/php]



    [php] echo $row['gdtitle'];[/php]
    [php] echo $row['pos'];[/php]
    [php] echo $row['rat'];[/php]
    [php] echo $row['sho'];[/php]
    [php] echo $row['pas'];[/php]
    [php] echo $row['dri'];[/php]
    [php] echo $row['def'];[/php]
    [php] echo $row['hea'];[/php]
    [php] echo $row['ski'];[/php]
    [php] echo $row['wft'];[/php]
    [php] echo $row['price'];[/php]

    [php]
    $i++;
    }
    }

    [/php]

    • Jane Wilson says:

      Hi Akif,

      Each section inside a [php] shorttag is evaluated as its own block of content so starting an if statement in own block and ending it in another will not work. If you move it all into one block you should have more luck.

      Thanks,
      Grant

  242. I am using Easy Table plug-in (http://wordpress.org/plugins/easy-table/) and its shortcode [table] to display the data generated by within php code.

    [table] shortcode handles the data between the tags so I am having trouble spread the data to show inside the table. I can only enter all data to the first cell using the snippet.

    anyone wanna tackle this challenge? I would appreciate any help. Help~

  243. Thanks for your post Micah! I couldn’t figure out why my include statement (and using the absolute path) wasn’t working. Using the format that you suggested:
    include(‘files/file.php’);
    worked! Thanks!

  244. Umm.. OK.. Even this comment box strips out the HTML. I normally have HTML around the #ClientIP. The HTML makes the IP address bold and the color red.

    • Chris Gilchrist says:

      Make it a snippet then instead using the plugin and embed using the shortcode that will prevent it happening

  245. [php] if ($_GET[qTz] === ‘about’) { echo ”; } else { echo ” } [/php]

    is returning this error:

    Parse error: syntax error, unexpected ‘>’

    Advice?

    Thank you!

  246. my code was stripped:

    [php] if ($_GET[qTz] === ‘about’) { echo ‘lessThandiv class=”articlz” id=”bone”greaterThan’; } else { echo ‘lessThandiv class=”articlz” id=”bone” style=”display:none;”greaterThan’ } [/php]

  247. Hi,

    can I pass some parameters to my snippet like:

    [php function=1 year=2008]

    Is that possible anyhow?

    Cheers, Marco

Trackbacks

  1. [...] WordPress plugin to easily Allow PHP in Posts and Pages – Hit Reach __________________ Linked In :: Last.fm :: Twitter :: Flukle :: Gowalla :: Nike+ :: Dribbble :: FFFFound [...]

  2. [...] Allow PHP in Posts and Pages does just what it says – it lets you add PHP code to any page or post using some simple shortcode.  You can also make it even easier to add code by adding snippets in it’s settings panel, which gives you a very short code that you can use over and over. [...]

Add Comment Register



Leave a comment

*


8 − two =

What Our Clients Say

James AgateJames Agate
Managing Director
Skyrocket SEO

Chris and his team are patient, responsive and have a sense of humour even when I asked them to change something that I'd insisted upon initially. Would definitely recommend to anyone looking for an awesome WordPress development and design team.

Richard SedleyRichard Sedley
Director
Seren

Hit Reach were really easy to deal with and provide exemplary service. They implemented exactly what we wanted and guided us when we were uncertain about the solution. A highly professional and cost effective solution – what's not to love.

Roger GreenRoger Green
Director
Best4tyres.com

Hit Reach got it absolutely right. They embraced the challenge and complexity of the site, and exceeded expectation with quick response times and great service.

Our Key Services
Menu