【问题标题】:I need to extract variables from a shortcode but I'm stuck我需要从简码中提取变量,但我被卡住了
【发布时间】:2016-04-28 02:26:57
【问题描述】:

这就是我正在做的事情:

我的帖子只包含一个带有嵌入视频的短代码:

[video width="1280" height="720" mp4="http://myurl/wp-content/uploads/2016/01/VID_20160114_202806.mp4"][/video]

我想要的只是“mp4”变量,但它可能有不同的名称,具体取决于编码,所以假设我只需要 [2] 值。

请记住,上面的简码就是帖子中的全部内容。这是我的工作:

 $atts = array();
 $atts = shortcode_parse_atts( $post->post_content );
 //then I use $atts[2];

这很失败。 我收到以下通知:Undefined offset: 2

如果我运行print_r,这是我得到的扭曲数组:

Array
(
    [0] => [video
    [width] => 1280
    [height] => 720
    [1] => mp4=" http:="" myurl="" wp-content="" uploads="" 2016="" 01="" vid_20160114_202806.mp4"][="" video]

(诚然,这是因为它被打印在一个 html 标记中而变得更糟,它解释了所有这些引号;关键是,参数的提取失败)

我认为$post->post_content 不是shortcode_parse_atts 想要的。它需要一串属性。但是,我如何获得属性字符串? (我知道,正则表达式,对吗?)

【问题讨论】:

  • 是的,在这种情况下你可以使用正则表达式

标签: php arrays wordpress extract shortcode


【解决方案1】:

这就是短代码的设置方式:

function my_shortcode($atts){
    $atts = shortcode_parse_atts(array(
         //default values go here.  
    ), $atts);
}

现在您应该可以按预期正确接收值,并且可以使用$atts['width']$atts['height']$atts['mp4'] 访问它们。

【讨论】:

    【解决方案2】:

    感谢Ohgodwhy,我意识到这是要走的路。但是,它会产生一个问题,因为第三个值可能具有不同的名称,具体取决于视频的编码。

    但是我用正则表达式解决了(我不想...因为懒惰...)

    if (preg_match('%\[video \w+="\w+" \w+="\w+" \w+="(.*)"\]\[/video\]%', $post->post_content)) {
            preg_match_all('%\[video \w+="\w+" \w+="\w+" \w+="(.*)"\]\[/video\]%', $post->post_content, $result);
    
    // now I can use $result[1][0] to get the video url; (I figured [1][0] by trial and error so don't ask why)
    

    【讨论】:

      【解决方案3】:

      我认为您应该首先使用简码正则表达式匹配帖子内容中的简码,然后使用函数shortcode_parse_atts() 解析每个简码字符串中的属性。

      另外,请注意调用此函数的正确方法是将简码参数的字符串传递给函数,而不是整个简码字符串。

      以这个简码为例。

      [video width="1280" height="720" mp4="http://myurl/wp-content/uploads/2016/01/VID_20160114_202806.mp4"][/video]
      

      你应该:

      shortcode_parse_atts( 'width="1280" height="720" mp4="http://myurl/wp-content/uploads/2016/01/VID_20160114_202806.mp4"' );
      

      而不是

      shortcode_parse_atts( '[video width="1280" height="720" mp4="http://myurl/wp-content/uploads/2016/01/VID_20160114_202806.mp4"][/video]' );
      

      回到你的问题,我觉得你可以参考这段代码sn-p:

      $shortcode_pattern = get_shortcode_regex( ['video'] );
      if ( preg_match_all( '/' . $shortcode_pattern . '/s', $post->post_content, $m ) ) {
          // $m[3] – The shortcode argument list 
          foreach( $m[3] as $atts_string ) {
              $atts = shortcode_parse_atts( $atts_string );
          }
      }
      

      参考:

      【讨论】:

        猜你喜欢
        • 2013-01-09
        • 2011-03-02
        • 1970-01-01
        • 1970-01-01
        • 2023-02-09
        • 2019-08-28
        • 2022-01-04
        • 2018-04-22
        • 1970-01-01
        相关资源
        最近更新 更多