0

I have a simple PHP script that I want to load whenever someone lands on a homepage. It is fetching data from another service and then I have to display it in a container on the homepage.

I was looking at options on how to enable PHP code in an HTML box that is provided by Wordpress.

I found several plugins that claim to enable parsing and execution of PHP scripts inside the HTML box/text-box. However, none of them are working for me. I tried PHP Code Widget in the last and I noticed that somehow my PHP code is automatically converted to HTML comments. See example below --

After activating the plugin, I entered this in the text view (I tried visual view as well) of the HTML box.

<?php
echo "Hello World!";
?>

However, nothing showed up on the page. When I did an inspect element, it showed me something like this --

<div class="htmlbox-content">
       <!--?php
          echo "Hello world!";
       ?--> 
</div>

It had automatically converted the opening bracket of my PHP code to an HTML comment. I tried editing it inline, however whenever I remove the "--", they come back again i.e. it doesn't let me alter them.

I am not 100% sure if I am doing it right. However, I could not find anything wrong in the steps I have been performing. How do I fix this?

Also, I am aware that enabling PHP code in HTML/textbox is not a great solution. However, I could not find anything that points me to how I can achieve the same goal otherwise. Any tutorial/pointers otherwise would be really appreciated!

Some details:

I am on a network enabled Wordpress 3.9.2

I tried enabling just for the website as well as enabling it across the network. Same result in both scenarios.

The plugin is compatible for versions 2.8 and higher and supported uptil 4.0.1, hence should ideally work. I have also tried other plugins with different variations on what they support, however none of them seem to work.

  • 2
    It almost sounds like you want a Shortcode where the user enters a specific format and on the front-end it proesses the shortcode and spits out the results fetched from whatever server you're using. – Howdy_McGee Mar 23 '15 at 18:24
  • 2
    @user69485 , i suggest you to upgrade site to WP 4.1 , lot of cool things happened in WP V4 – bravokeyl Mar 23 '15 at 18:34
2

As you have already understated, running executable PHP inside a text box is not a good idea. It isn't only just not a good idea, but a terrible idea. This creates a loop hole in your security which can be very easily exploited by a hacker.

I would suggest writing your own custom widget for this functionality. It is really easy adding a custom sidebar to the top of your index.php for that specific purpose into which you can just simply drop your custom widget into. Have a look at register_sidebar(). There are also plenty tutorials out there on this specific subject on how to add a custom sidebar in your theme

As for the widget, look at the Widget API. I (with some assistance from @birgire ;-)) have also done a recent widget which displays categories which you can use as a base for your widget. You can simply code your custom code from the selected service into the widget method. You can make this very dynamic.

Here is basic skeleton you can use. To make this work, you only need to replace // ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END with your custom php code which is inside the widget() method (NOTE: Requires PHP 5.4+)

class Custom_Services extends WP_Widget 
{

    public function __construct() 
    {
        parent::__construct(
            'widget_custom_service', 
            _x( 'Custom Service Widget', 'Custom Service Widget' ), 
            [ 'description' => __( 'Displays information from a custom service.' ) ] 
        );
        $this->alt_option_name = 'widget_custom_service';

        add_action( 'save_post', [$this, 'flush_widget_cache'] );
        add_action( 'deleted_post', [$this, 'flush_widget_cache'] );
        add_action( 'switch_theme', [$this, 'flush_widget_cache'] );
    }

    public function widget( $args, $instance ) 
    {
        $cache = [];
        if ( ! $this->is_preview() ) {
            $cache = wp_cache_get( 'widget_services', 'widget' );
        }

        if ( ! is_array( $cache ) ) {
            $cache = [];
        }

        if ( ! isset( $args['widget_id'] ) ) {
            $args['widget_id'] = $this->id;
        }

        if ( isset( $cache[ $args['widget_id'] ] ) ) {
            echo $cache[ $args['widget_id'] ];
            return;
        }

        ob_start();

        $title          = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Category Posts' );
        /** This filter is documented in wp-includes/default-widgets.php */
        $title          = apply_filters( 'widget_title', $title, $instance, $this->id_base );

        // ADD YOUR CUSTOM PHP CODE HERE FOR EXECUTION TO DISPLAY ON FRONT END

        echo $args['after_widget']; 

        if ( ! $this->is_preview() ) {
            $cache[ $args['widget_id'] ] = ob_get_flush();
            wp_cache_set( 'widget_services', $cache, 'widget' );
        } else {
            ob_end_flush();
        }
    }

    public function update( $new_instance, $old_instance ) 
    {
        $instance                   = $old_instance;
        $instance['title']          = strip_tags( $new_instance['title'] );
        $this->flush_widget_cache();

        $alloptions = wp_cache_get( 'alloptions', 'options' );
        if ( isset($alloptions['widget_custom_service']) )
            delete_option('widget_custom_service');

        return $instance;
    }

    public function flush_widget_cache() 
    {
        wp_cache_delete('widget_services', 'widget');
    }

    public function form( $instance ) 
    {

        $title      = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
        ?>

        <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" />
        </p>

    <?php
    }

}

add_action( 'widgets_init', function () 
{
    register_widget( 'Custom_Services' );
});
1

The PHP Code Widget does not modify the Text or Visual editor box, or the standard "Text" widget; it adds a "PHP Code" widget, which you'll find under Appearance > Widgets > Available Widgets.

If you want to display your script within the body of the post or page, you should create a Shortcode. The basic example from the API would work for "Hello World"; you would add this to your theme's functions.php (or better yet create a plugin):

function foobar_func( $atts ){
    return "Hello World";
}
add_shortcode( 'foobar', 'foobar_func' );

Then in your post or page, type the [foobar] shortcode to display your script. Add the code for your custom PHP script, and return the final output to be displayed (you don't want to echo from within the shortcode function).

Or, creating the shortcode in a plugin will keep it available even if you switch themes:

<?php
/**
 * Plugin Name: wpse-182025
 * Description: Creates [wpse-182025] shortcode to execute custom PHP script on posts, pages, etc
 * Plugin URI: http://wordpress.stackexchange.com/a/182026/54569
 * Version: 1.0
 */

function wpse_182025_func() {
    // Add your custom PHP script
    $output = "Hello World";
    return $output;
}
add_shortcode( 'wpse-182025', 'wpse_182025_func' );
?>

Add the above code to /wp-content/plugins/wpse-182025/wpse-182025.php, OR create the /wpse-182025/wpse-182025.php folder and file locally, add to a zip file, and upload using Plugins > Add New > Uploads. Display the shortcode with [wpse-182025]. You can modify any of the example plugin code as needed.

  • 2
    Function names should contain lower case letters and numbers only, WPSE_182025_func should be wpse_182025_func – Pieter Goosen Mar 23 '15 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.