How To Add PHP Code to Elementor

How To Add PHP Code to Elementor

In this tutorial we are going to show you how to add PHP Code to Elementor.

At some point you may find yourself needing to add some PHP code to a certain part of a page template that is built using Elementor. Elementor by default however only has elements to add HTML and Javascript and doesn’t allow the adding of php code into any of those elements or the text block. So today we are going to show you how to add custom php code to any Elementor page by creating a shortcode in your themes functions.php.

Create a Shortcode to add PHP Code to Elementor

Using the WordPress shortcode API guidelines, in your functions.php file (or other include depending on your theme setup) add the following code:

// Shortcode to output custom PHP in Elementor
function wpc_elementor_shortcode( $atts ) {
    echo "This is my custom PHP output in Elementor!";
}
add_shortcode( 'my_elementor_php_output', 'wpc_elementor_shortcode');

Be sure to name the function and the shortcode something relevant to what you’re trying to output on the page, this is only a simple example.

If you need to output multiple custom php functions that is separate from the first you will need to copy the code above and make sure you change the name of the shortcode. You can not have the same name for two different shortcodes.

Add The Shortcode to a Page Using Elementor

Now that your shortcode has been added and registered it can be called into Elementor using a “text block” or the “shortcode” widget element. Navigate over to the page that you are wanting to add the custom php to.

From there, add a Elementor shortocode element with your newly created shortcode called within it. For this guide the shortcode is [my_elementor_php_output]

Now that the shortcode is in your Elementor page layout, you can view the live results of the page to ensure the output is as expected.

In Summary

Obviously, there are more possibilities than using echo using this solution; it can be expanded to serve any functionality possible with the WordPress Shortcode API, such as shortcodes that handle attributes.

We here at WP Codeus hope this quick guide helps other people facing the same issue; trying to add your own PHP code to any Elementor page.

Need Help with your Website?

Our Experts can handle any customization or developement at a reasonable price.

Get a Quote

Looking for more?

Here are some other articles that we think you will be interested in!