Как добавить другой параметр для использования в файле php при включении файла php, используя шорткод в WordPress - PullRequest
0 голосов
/ 15 июня 2019

Я использую шорткод для включения PHP-файла в страницу WordPress.Это прекрасно работает.Но мне нужно добавить параметр, а не только имя файла.

Я могу добавить еще один параметр в шорткод, но я не вижу, как я могу дать другой параметр (например, «заголовок») для использованияэто в 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');

1 Ответ

0 голосов
/ 15 июня 2019

Используйте атрибуты шорткода с известными атрибутами и, при необходимости, заполняйте значения по умолчанию.

  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>';
...