1

I am wondering if there is a way to create a shortcode to use in the visual page builder on a page in Wordpress that would allow me to use it as a PHP include. I need to add some PHP code from a file called form.php into my page and the visual page builder only let's you add HTML. I would prefer not to use a plug-in if possible. I need to use this code but it's not recognizing it.

<?php include 'form.php';?>

2 Answers 2

2

Absolutely - you can have a shortcode that takes one parameter (the file to include) and simply outputs its content:

add_shortcode('include', 'include_php_file');
function include_php_file($atts=array(), $content='') {
    $atts = shortcode_atts(array(
        'file' => ''
    ), $atts);
    if(!$atts['file']) return ''; // needs a file name!
    $file_path = dirname(__FILE__).'/'.$atts['file']; // adjust your path here
    if(!file_exists($file_path)) return '';
    ob_start();
    include($file_path);
    $html = ob_get_contents();
    ob_end_clean();
    return $html;
}

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for answering, do I add this in the functions.php file? and then what would the shortcode be that I can use on the page?
Oh - sorry, missed that part, didn't I? So yes, you would add this to your theme's function.php file. (If it's not your own theme, I hope you made a child theme!) Then to use it, simply put this in any page or post's content box: [include file='form.php']
0

You can also edit the template for that page and conditionally include that file only for that post.

es:

if( is_page('contact') include('path/to/file.php');

if you need that file in more than one page pass an array to is_page:

if( is_page( array( 'about-us', 'contact', 'management' ) ) 
     //either in about us, or contact, or management page is in view
     include('path/to/file.php');
else
     //none of the page about us, contact or management is in view

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.