簡體   English   中英

從Wordpress中的網址將變量傳遞給簡碼

[英]Pass variables to shortcode from the url in Wordpress

我做了一個簡單的WP插件,它將從calameo.com獲取一些文檔並以一種不錯的方式展示它們。 我為此做了一個自定義的簡碼 我們稱之為“短代碼”…

我將使用[Shortcode vendor=vendor1]僅顯示與賣方有關的文檔,並且我知道該怎么做。

我需要做的是將參數值從url傳遞到短代碼,但是我還沒有找到實現它的方法。

任何幫助表示贊賞。

與德里克(Derek)達成一致,這個問題尚不清楚。

據我了解,您想提取在包含您的簡碼的頁面的URL上傳遞的參數(例如“供應商”參數),並確保簡碼參數可以動態獲取此值?

如果是這樣,那就沒有意義了:短代碼用於生成頁面的代碼(HTML,JavaScript等在瀏覽器中運行的任何內容),並在結果頁面中完全消失,這意味着您的行為不會有所不同除非您的短代碼生成的代碼(JavaScript)包含一些“供應商”變量(可以從參數中獲取其值),然后依次生成某些內容(HTML,SVG…),否則,某種棘手的代碼..

要從URL傳遞一些變量,您將在短代碼中使用$_GET ,如以下示例所示:

if( ! function_exists('this_is_my_shortcode') ) {
    function this_is_my_shortcode( $atts, $content = null ) {
        // Attributes
        $atts = shortcode_atts( array(
            'vendor' => '',
            'thekey1'    => isset($_GET['thekey1']) ? sanitize_key($_GET['thekey1']) : '',
            'thekey2'    => isset($_GET['thekey2']) ? sanitize_key($_GET['thekey2']) : '',
        ), $atts, 'my_shortcode' );

        // Variables to be used
        $vendor_value = $atts['vendor'];
        $value1 = $atts['thekey1']; // the value from "thekey1" in the url
        $value2 = $atts['thekey2']; // the value from "thekey2" in the url

        // Your code … / …


        if( ! empty( $value1 ) )
            $value1 = ' | Value 1: ' . $value1;

        if( ! empty( $value2 ) )
            $value2 = ' | Value 2: ' . $value2;

        // Output: Always use return (never echo or print)
        return '<p>Vendor: ' . $vendor_value . $value1 . $value2 . '<p>';
    }
    add_shortcode("my_shortcode", "this_is_my_shortcode");
}

代碼進入您的活動子主題(或主題)的function.php文件中。 測試和工作。

用法:

  • 網址類似: http://www.example.com/your-page/?thekey1=document1&thekey2=document2 : http://www.example.com/your-page/?thekey1=document1&thekey2=document2 document1&thekey2= http://www.example.com/your-page/?thekey1=document1&thekey2=document2
    (每個參數鍵/值對以&字符分隔)
  • shordcode:
    • 在wordPress頁面/后文本編輯器中: [my_shortcode vendor="vendor1"]
    • 在php代碼中: echo do_shortcode( "[my_shortcode vendor='vendor1']" );

您將獲得生成的html輸出:

<p>Vendor: vendor1 | Value 1: document1 | Value 2: document2</p>

暫無
暫無

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

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