【问题标题】:Read and extract attributes from wordpress video shortcode?从 wordpress 视频短代码中读取和提取属性?
【发布时间】:2016-02-14 09:32:41
【问题描述】:

我的目的是从这样的事情出发,取自post_content

[video width="1080" height="1920" webm="http://path/file.webm" autoplay="true"][/video] 

到这样的数组:

Array( 
    width=>1080, 
    height=>1920,
    webm=>"http://path/file.webm",
    autoplay=>"true"
);

当然取决于用户在视频短代码中输入的内容,或多或少的配对。

我已经阅读了关于 shortcode_atts 的 Shortcode_API 和 instructions。我无法找到关于如何以数组形式获取这些属性的简单说明。

尽管人们一直建议我不能使用shortcode_atts,因为这个wordpress函数要求属性已经在一个数组中

我知道如何使用正则表达式或多或少地完成上述操作。但是是否有任何 wordpress 明显的方法可以将简码属性转换为数组?我知道应该有。

例如,这是行不通的:

shortcode_atts( array(
                'width'    => '640',
                'height'   => '360',
                'mp4'   => '',
                'autoplay' => '',
                'poster'   => '',
                'src'      => '',
                'loop'     => '',
                'preload'  => 'metadata',
                'webm'   => '',
        ), $atts);

因为 $atts 应该是一个数组,但我只有一个来自$post_content 的字符串,它看起来像这样:

[video width="1080" height="1920" webm="http://path/file.webm" autoplay="true"][/video] 

请注意:我没有实现短代码功能或类似的功能。我只需要阅读在帖子内容中添加的 wordpress 视频短代码。

【问题讨论】:

标签: php wordpress attributes extract shortcode


【解决方案1】:

如果有人对上述问题感兴趣,答案是 shortcode_parse_atts 函数,如 here 所述。

【讨论】:

    【解决方案2】:

    这是一个非常紧凑的正则表达式解决方案:

    代码

    <?php
        $input = '[video width="1080" height="1920" webm="http://path/file.webm" autoplay="true"][/video]';
    
        preg_match_all('/([A-Za-z-_0-9]*?)=[\'"]{0,1}(.*?)[\'"]{0,1}[\s|\]]/', $input, $regs, PREG_SET_ORDER);
        $result = array();
        for ($mx = 0; $mx < count($regs); $mx++) {
            $result[$regs[$mx][1]] = is_numeric($regs[$mx][2]) ? $regs[$mx][2] : '"'.$regs[$mx][2].'"';
        } 
    
        echo '<pre>'; print_r($result); echo '</pre>';
    ?>
    

    结果

    Array [width] => 1080 [height] => 1920 [webm] => "http://path/file.webm" [autoplay] => "true" )

    【讨论】:

      【解决方案3】:

      在我看来(至少在 4.7 版中)您使用 add_shortcode() 指定的函数会将短代码参数放入数组中:

      如果你像这样添加短代码:

          add_shortcode('my_shortcode_name', 'my_shortcode_function');
      

      那么像这样的 'my_shortcode_function' 会有一个属性数组:

      function my_shortcode_function($atts) {
      // this will print the shortcode's attribute array
      echo '<pre>';print_r($atts);echo '</pre>';
      }
      

      ...瑞克...

      【讨论】:

        猜你喜欢
        • 2014-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 2014-02-13
        • 2020-06-30
        • 2023-04-05
        相关资源
        最近更新 更多