如何添加另一个参数以在 php 文件中使用,同时在 wordpress 中使用短代码包含 php 文件

How to add another parameter to use in the php file while including a php file using shortcode in wordpress

我使用短代码将 PHP 文件包含到 WordPress 页面中。那很好用。但是我需要添加一个参数,不仅仅是文件名。

我可以在短代码中添加另一个参数,但我不明白如何提供另一个参数(即 "title")以在 PHP 文件中使用它。

实际的短代码看起来像 [include file=PATH.phpfile]。我会添加另一个参数 title=titleexample 以在 PHP 文件中使用它。

我使用此代码来包含 php-文件(工作正常):

function include_shortcode_function($attrs, $content = null) {
    if (isset($attrs['file'])) {
        $file = strip_tags($attrs['file']);
        if ($file[0] != '/')
            $file = ABSPATH . $file;
        ob_start();
        include($file);
        $buffer = ob_get_clean();
        $options = get_option('includeme', array());
        if (isset($options['shortcode'])) {
            $buffer = do_shortcode($buffer);
        }
    }
    return $buffer;
}

add_shortcode('include', 'include_shortcode_function');

使用已知属性的短代码属性,并在需要时填写默认值。

  function include_shortcode_function($atts) {
        $attrs = shortcode_atts( array(
            'file' => '',
            'title'  =>  ''
        ), $atts );

       //Get the file and title details 
        $files = esc_attr($attrs['file']);
        $title = esc_attr($attrs['title']);

        if (isset($files)) {
            $file = strip_tags($files);
            if ($file[0] != '/')
                $file = ABSPATH . $file;
                //Use this variable in included file for title.
                $pagetitle = $title;
            ob_start();
            include($file);
            $buffer = ob_get_clean();
            $options = get_option('includeme', array());
            if (isset($options['shortcode'])) {
                $buffer = do_shortcode($buffer);
            }
        }
        return $buffer;

    }


add_shortcode('include', 'include_shortcode_function');

像这样使用简码。

[include file=PATH.phpfile title= titleexample]

让我们包含 example.php 文件。在 example.php 文件中使用变量 $pagetitle.

echo '<p class="title">'.$pagetitle.'</p>';