• Hi there,

    I am trying to use a shortcode to insert a PHP file, but can’t get the code right.

    This is what I have:

    function nc_scroll( $atts, $content = null ) {
     
        extract( shortcode_atts( array(), $atts ) );
     
        $nc_scroll_c='INCLUDE FILE HERE';
     
        return $nc_scroll_c;
    }
    add_shortcode('nc_calendar', 'nc_scroll');

    Can anyone tell me how I can add the included file here?
    $nc_scroll_c='INCLUDE FILE HERE';

    The path is /wp-content/themes/jobseek-child/inc/new-competition-calendar.php.

    Many thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • I assume you want to execute the PHP file?
    Since it’s in the theme, you could use get_template_part() although this does a require not an include. But it does look in the active theme folder and child folder for you. https://developer.wordpress.org/reference/functions/get_template_part/ Otherwise, you would need to call get_template_directory() to get the theme folder. Themes often use
    require get_template_directory() . '/inc/whatever.php';
    Be aware that shortcodes should not output anything, though. So to be safe, you should turn output buffering on, then call it, then return the the buffer.
    Also, there is no need to extract attributes if you don’t expect any.

    It might be better to refactor the code so there is a single function that builds the output. That function is called from the existing file, and also from the shortcode.

    Use this code in functions.php

    function PHP_Include($params = array()) {

    extract(shortcode_atts(array(
    ‘file’ => ‘default’ //Use the real file name here
    ), $params));

    ob_start();
    include(get_theme_root() . ‘/’ . get_template() . “/$file.php”);
    // Choose which directory the file is located

    return ob_get_clean();
    }

    add_shortcode(‘include’, ‘PHP_Include’);

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘including a PHP file via shortcode?’ is closed to new replies.