簡體   English   中英

如何在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頁面中。 這工作正常。 但我需要添加一個參數,而不僅僅是文件名。

我可以在短代碼中添加另一個參數,但我沒有看到,如何在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>';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM