Создание шорткода WordPress для повторного использования - PullRequest
0 голосов
/ 01 апреля 2020

Я создал шорткод WordPress, который выводит форму. Ниже приведен мой шорткод

function testcode(){
   echo "<h1>TEST</h1>";
}

add_shortcode ("test-code", "testcode");

Я хочу иметь возможность включать <h1>Test</h1> в такой файл что пользователи, которые хотят переопределить шорткод, могут просто создать новый файл.

Так что-то вроде

  function testcode(){
      //load html from a a file like templates/test.php
  }
 add_shortcode("test-code","testcode");

Как мне сделать это многоразовым и расширяемым?

1 Ответ

1 голос
/ 01 апреля 2020

Вы можете добавить параметр файла в шорткод загрузить отдельный файл.

function testcode( $atts = [], $content = null, $tag = '' ){
     // normalize attribute keys, lowercase
     $atts = array_change_key_case((array)$atts, CASE_LOWER);

     // override default attributes with user attributes
     $atts = shortcode_atts(
        [
            'file' => 'default.php',
        ],
        $atts, 
        $tag
    );
    ob_start();

    // echo "/some/path/{$atts['file']}";
    require "/some/path/{$atts['file']}";

    $contents = ob_get_contents();
    ob_end_clean();
    return $contents;
}
add_shortcode("test-code","testcode");

echo do_shortcode( '[test-code file="sagar"] ');

Ссылка: https://developer.wordpress.org/plugins/shortcodes/shortcodes-with-parameters/ https://developer.wordpress.org/reference/functions/do_shortcode/

...