【问题标题】:Simplify a Wordpress shortcode (or: "custom shortcode")简化 Wordpress 简码(或:“自定义简码”)
【发布时间】:2014-04-22 10:18:38
【问题描述】:

我使用简码在我的 Wordpress 模板上显示我的图片。

[photo id="13927101803" caption="Some text"] // Flickr
[photo id="mqEqHAC3rK"] // Instagram, no caption

因为我用 Markdown 写帖子,所以当我要包含 10 张或更多照片时,写这些 [attr="ibutes"] 有点无聊。 这就是为什么我希望简化这些照片,包括拥有类似的东西:

[13927101803 "Caption"] // Flickr
[mqEqHAC3rK] // Instagram

// Causes a conflict with the links in Markdown [this is](http://a-link)… ?

当我保存帖子时,它会运行一个检测短代码的钩子,调用 Flickr/Instagram API 以获取源图像 url 并将其存储到数据库中(每个帖子的每张照片的数组)。

这是我当前捕获短代码的代码:http://pastebin.com/TVEQKudg

有什么方法可以简化这些调用?或者另一个想法来快速调用它并且不使用这些长短代码?

【问题讨论】:

  • 用简单的语言解释。你想达到什么目标?
  • 使用这个[13927101803 "Caption"]而不是这个[photo id="13927101803" caption="Some text"] :)
  • 这个13927101803 和这个mqEqHAC3rK 以后会改变吗?这些 id 是否适用于单个图像>
  • 是的,每张图片都会发生变化,但对于 flickr,ID 始终为 11 位,对于 Instagram,ID 始终为 10 [a-zA-Z0-9]
  • 不,你不能。 Wordpress 短代码必须具有描述短代码的唯一占位符,就像您拥有 [photo ...] 一样。这就是为什么你有属性是为了修改动态数据key/value对。

标签: php regex wordpress preg-match


【解决方案1】:

好的,你去:

/\[(\d{11}|\w{10})(?:\s*"([^"]+)")?\]\/

假设你有这个内容:

简单测试 [13927101801 "Caption"] [mqEqHAC3rK "caption"]简单 测试 简单测试 简单测试a 简单测试 简单测试a 简单测试简单测试a [13927101801]

那么你可以这样做:

$content = do_shortcode(get_the_content());
preg_match_all('/\[(\d{11}|\w{10})(?:\s*"([^"]+)")?\]\/', $content, $matches);

$matches = array_slice($matches, 1);
$matches = call_user_func_array( 'array_map', array_merge(array(NULL), $matches) );

var_dump($matches);

输出:

array (size=3)
  0 => 
    array (size=2)
      0 => string '13927101801' (length=11) // <-- ID
      1 => string 'Caption' (length=7)      // <-- Caption content
  1 => 
    array (size=2)
      0 => string 'mqEqHAC3rK' (length=10) // <-- ID
      1 => string 'caption' (length=7)     // <-- Caption content
  2 => 
    array (size=2)
      0 => string '13927101801' (length=11) // <-- ID
      1 => string '' (length=0)           // <-- No Caption content

您将获得id 和(可选)caption 的数组

【讨论】:

  • 哇!这真的超出了我的技能。我可以像阅读中文一样阅读您的正则表达式,或者如果我的猫坐在我的键盘上……无论如何感谢您的建议,我会尽快对其进行测试。
  • 好的,你的正则表达式模式是金块,它就像一个魅力!谢谢你的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
相关资源
最近更新 更多