nested-loops - get_the_content() 和无限嵌套循环中的 wordpress 简码
问题描述
首先,很抱歉这个冗长的主题,但我没有找到其他方法来解释这个问题......
我遇到了在 get_the_content() 中执行的短代码以及可能发生的无限嵌套循环的管理问题。
我的插件用作简码来显示作为参数传递的特定类别列表的帖子。短代码也可以在页面、帖子或小部件上使用。可以这样概括:
Root Post/Page/Widget body with [shortcode category_slug_list="category_slug1"]
=> post 1 of category with slug1 is displayed
post 2 of category with slug1 is displayed
...
...
post n of category with slug1 is displayed
每个帖子都显示在循环中:
$content = get_the_content();
$content = apply_filters('the_content', $content);
如果在帖子上使用它,这里的主要问题是帖子不得属于短代码指定的类别之一,以避免无限嵌套循环。
当属于某个类别的帖子处于第一级 depth时,对此的管理是通过以下方式完成的:
if (is_single()) {
if (in_category($category_slug_array)) {
// The function must not proceed with this post !!!
$out = '<div>To proceed inside a post, the post MUST not belong to one of the categories asked by "category_slug_list" option, to avoid infinite nested loop...</div>';
return $out;
}
}
它之所以有效,是因为 (is_single) 与第一级深度相关,而这里的第一级是一篇文章。
但是,例如,当第一级深度是页面时,当显示的其中一个帖子有自己的简码时,就会出现问题。由于使用 get_the_content() 检索帖子的内容,当执行其中的简码时,我找不到检索上下文的方法,因为 is_single() 返回 false,因为它与根页面相关,而不是我们从中获得 get_the_content() 值的当前帖子。
例子:
Root Page body with [shortcode category_slug_list="category_slug2"]
=> post 1 of category with slug2 displayed
post 2 of category with slug2 displayed
post 2 body with [shortcode category_slug_list="category_slug2"]
...
...
post n of category with slug2 displayed
从这个例子中,有没有办法获得“post 2”上下文,我的意思是验证它是一个帖子,然后检查它的 in_category 函数?任何线索,想法,建议都将受到欢迎......
解决方案
所以,我终于找到了解决这个问题的方法:
我发现的唯一方法是能够将帖子 ID 作为属性传递给嵌套的短代码。
在简码函数中,在帖子循环中,如果找到简码,我会在帖子内容中使用 str_ireplace 添加属性:
$content = str_ireplace("[shortcode-function-name",'[shortcode-function-name post_id="'.$post->ID.'"',$content);
因此,在短代码函数的开头,我检索了 post_id 属性:
extract(shortcode_atts(array(
"post_id" => '',
"other_attribute" => 'default_value',
...
...
"last_attribute" => 'default_value'
), $atts));
然后,除了在根帖子的情况下进行第一次检查之外,我现在可以检查帖子 ID:
if ($post_id) {
if (in_category($category_slug_array,$post_id)) {
// The function must not proceed with this post !!!
$out = '<div>To proceed inside a post, the post MUST not belong to one of the categories asked by "category_slug_list" option, to avoid infinite nested loop...</div>';
return $out;
}
}
如果它可以帮助尝试在嵌套循环中使用短代码函数的人,具体取决于帖子的具体情况......
推荐阅读
- php - Magento 2.2.2 错误:配置文件已更改。运行 app:config:import 或 setup:upgrade 命令同步配置
- laravel - 我的 Laravel 容器中的路由没有更新
- android - 构建一个 android 客户端应用程序以与支持 HTTP2 的流服务交互
- c - 无法将较小的数组复制到 C 中较大的预填充数组中
- robocopy - Robocopy - 错误 124 (0x0000007C) 创建目标目录
- python - 如何在我的 pygame 程序中实现此功能?
- javascript - 如何在有限宽度容器内和边栏旁边制作全页/窗口宽度图像?
- r - 按列名对包含字符串的行进行子集 - Grepl
- c++11 - 类的方法(在 shared_ptr 中)可以绑定到特征类中的静态函数吗?
- java - onclick 侦听器在片段中不起作用