【问题标题】:How to extract WordPress shortcode attributes from post content如何从帖子内容中提取 WordPress 短代码属性
【发布时间】:2014-01-04 15:53:31
【问题描述】:

在我关于 WordPress 的帖子中,我创建了未知数量的 my_player 类型的短代码并正确添加了挂钩。我想知道是否有某种类型的 WordPress 函数可以将您的内容和短代码名称传递给它,它可以为您提供一组匹配的短代码,它们的属性由属性名称索引。类似于我下面的代码...

$matches = get_shortcode_matches($content, "my_player");

for($i = 0; $i < sizeof($matches); $i++)
{
    $title = $matches[$i]['title'];
    $mp3 = $matches[$i]['mp3'];
    $soundcloud = $matches[$i]['soundcloud'];
}

我知道,当您使用 add_shortcode() 函数为短代码创建挂钩时,您可以像上面一样使用这些索引值,但我需要一个可以在以后和循环之外访问它们的函数。 WordPress有这样的功能吗?

【问题讨论】:

    标签: php html wordpress


    【解决方案1】:

    试试这个,

    <?php do_shortcode($content); ?>
    

    【讨论】:

    • 我已经在使用这些了。不过,这无助于提取任何属性及其值。
    【解决方案2】:

    有几种方法可以做到这一点: 1. 像上面一样编写你自己的 sn-p,在你的“mu-plugins”文件夹中插入以下内容

    // [myplayer attr="your-value"]
    function myplayer_func($atts) {
        extract(shortcode_atts(array(
            'title' => 'something',
            'mp3' => 'another something',
                    'soundcloud' => 'something else',
        ), $atts));
    
        return "attr= {$attr}";
    }
    add_shortcode('myplayer', 'myplayer_func');
    

    然后

    [myplayer title="something" mp3="another something" soundcloud="something else"]
    

    来自任何地方的任何帖子,包括子域。 2.可以使用ShortcoderGlobal Content Blocks等插件

    【讨论】:

    • 我说我已经设置了钩子和add_shortcode()函数。我知道你可以让它使用这个函数中的这些信息,但我想要一个函数,它给出短代码名称、要搜索的内容,并返回一个名称-值对数组。类似于我在原始帖子中编写的代码。
    • 在 WordPress 编码标准中不鼓励使用可怕的 extract() 函数。让你知道。
    【解决方案3】:

    我认为您不能通过使用现有操作来实现。 [shortcode_parse_atts] 没有附加事件。 您可以做到的唯一方法是 add_action/global 在您的每个 [add_shortcode] 相关函数/方法中都很有价值。

    类似:

    function doShortCode($atts, $content=null){
        global $my_shortcode_storage;
        $my_shortcode_storage['my_shortcode_1'][] = $atts;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      相关资源
      最近更新 更多