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
  • 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, 2015 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, 2015 at 18:34

4 Answers 4

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.

1
  • 2
    Function names should contain lower case letters and numbers only, WPSE_182025_func should be wpse_182025_func Mar 23, 2015 at 19:02
0

I have more complicated question. For view IOT data i'm using scripts incorporating: (1) php code for open database connection and read data, then this script have (2') html part for build for example dashboard or (2") even java script for view charts - parts (2) or (2') use php variables previously read from the database in part (1) of script. I call this script in my webserver using well known *.php file pathname directly and can view in web browser ready-to-use dashboard or chart or table. Now question is how to 'incorporate' this ready-to-view script into some webpage inside my webservice. I tried use 'PHP Snippets' with 'custom HTML' together - but they can't see each other. So data in PHP snippet is correct read from SQL database (I can see it by echoes it), but no matter this snippet is putted before or after 'custom PHP' block, the html block can't read data. I viewed final webpage source of code in my browser - I can exact localize my html code - but can't see source of 'shortcode' generated by 'PHP snippet'. I think better and more clear would be use something like 'show content of webpage inside subwindow or script-subwindow of the main page'. But I can't locate usefull add-on for make it. Script is not typical content like for example google ot youtube media - these contents are easy to incorporate - but not scripts. Pls help me manage this problem. In fact the 'sub-webpage' to view is 'view-dashboar.php' file or 'view-chart.php' in exact location on my hosting service (I can modify it, change name, I know pathname). My webbrowser process these scripts (no matter it include php first, then htmal or java). How to put this 'ready-to-view scripts content' into the main page and make this secure (preventing hackers attacks)? Best Regards

1
  • If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review
    – cjbj
    Oct 14, 2023 at 9:43
0

Yeah, it looks I'm answering myself... But generally I can see this topic was viewed over 3k times so it is still actual. My charts/tables/dashboards are now composed inside existing CSS Wordpress website! I tried POP-UP's - they works almost good - but code of POP-UP is fully loaded with the main page-code (as sub-code - in fact as PHP include action so variable names have to be unique! - many troubles!), this POP-UP sub-code is stilish accordingly to the page style (next problem...) - almost done... but it is not a 100% good choice - just is nice and simple to do with no extra payed add-ons inside Wordpress needed. But after tests I decided use HTML iframe sub-window to show the code as 'isolated' sub-window inside the page. Users have to be carrefully with iframes because of security reasons. For example if you try insert in iframe some page using iframe inside own content - it will be security problem - parent page will be blcoked (iframe inside iframe inside... === security malware). Similar problem is copyrights. We can not use other websites as own (because of copyryghts). But if we have own scripts with own stylish, with no iframe content inside and have fully copyrights - script just generating some content in webbrowser if we call it in our domain (like_https://somedomain.com/some_script.php) - best for me was show it inside the iframe child window-object. This subwindow is not stilih as parent page CSS website - it is isolated place. The childwindow code is not loaded with the page code - so it minimizes parent page weight code - it uses only URL links to the child content! I just use datepicker for decide date of samples to select from the chart, then send date as parameter with GET method to my script. I even made in HTML with CSS usage fully modal buttons-bar for make multi-action (from the same datepicker to different charts send GET method with the specified date), after send GET request to choosen by the user chart-type-button with specified date period - specific chart content is loaded inside the same iframe - works great! Google pages use iFrames frequently. It is flexible method - but we have to be carefully when use it. Maybe someone will just use my conclusions. Now I'm starting make own synoptic dashboard with redirection to many units showed inside synoptic (IoT). Worst is - everything have to be usefull inside Wordpress. Ughh... I'll do it anyway... Best Regards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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