【问题标题】:Create shortcode in PHP like those in WordPress像在 WordPress 中一样在 PHP 中创建短代码
【发布时间】:2015-05-07 07:09:29
【问题描述】:

我们正在尝试为我们创建一个基本系统。在我们想要创建像[gallery id="1"] 这样的短代码的地方,我们已经创建了这种短代码方式。

但是当涉及到以下内容时:

<h1>Some Title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer purus purus, scelerisque ut ex non, pharetra interdum tellus. Aenean sed libero a ipsum vestibulum feugiat quis quis magna. Mauris a condimentum mi, et feugiat leo.</p>
[gallery id="1"]

这是我的模板在编辑器中的样子。我如何阅读特定的[gallery id="1"] 并使其成为这样的功能

gallery(1)

有什么办法可以做到吗?我在这里使用的是所见即所得的编辑器,数据保存在 MySQL 数据库中。

【问题讨论】:

  • 你在使用任何 php 框架吗?

标签: php wordpress


【解决方案1】:

答案的开头:你必须使用这样的正则表达式:
#\[gallery id\=\"([0-9]+)\"\]#
这将获取所有 [gallery id="XXX"],() 将允许您捕获实际数字,然后调用您的 gallery(XXX) 函数

【讨论】:

  • 好的,但我怎样才能让它成为一个函数?有什么办法可以使它成为 PHP 标记?
  • 你说we have created this way of shortcodes,你对这个短代码做了什么?你做了gallery(int $id)函数吗?然后,您只需要调用该函数吗?我不知道 Word Press 插件如何使用这些标签(但我已经使用过它们)。就我而言,我使用的插件必须是JS插件,因为它似乎是在创建DOM之后添加元素......但我不知道你如何从JS调用PHP函数
  • 是的,我们只需要调用该函数。我们已经创建了这些函数。
【解决方案2】:

我创建了一个与框架无关的库来支持纯 PHP 项目中的 [shortcodes]https://github.com/thunderer/Shortcode。您只需要创建库实​​例,为您希望使用的短代码注册名称处理程序,一切顺利。

您的情况将这样解决(我从 README 中获取了这个示例):

// put those in the use block on top of your file:
use Thunder\Shortcode\Extractor;
use Thunder\Shortcode\Parser;
use Thunder\Shortcode\Processor;
use Thunder\Shortcode\Shortcode;

// code below does the magic:
$processor = new Processor(new Extractor(), new Parser());
$processor->addHandler('gallery', function(Shortcode $s) {    
    // return here any HTML code you need

    return $s->getParameter('id'); // this will return "id" parameter
});

$processor->process('[gallery id="2"]'); // will return "2"

【讨论】:

    【解决方案3】:

    我认为 RegEx 模式应该可以工作。 抱歉,我不太擅长 RegEx,但这是我的模式:

    http://regexr.com/3auv2

    【讨论】:

    • 感谢您的努力。是的,它会解决它。但我想将其转换为 任何解决方案?
    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多