【问题标题】:Wordpress add a div around All images in Content section of "custom post type"Wordpress 在“自定义帖子类型”的内容部分中的所有图像周围添加一个 div
【发布时间】:2021-10-05 23:45:15
【问题描述】:

我想在特定自定义帖子类型的内容部分中的所有图像周围放置一个 div。我试图将我在这里找到的问题的一些答案拼凑在一起。但是由于我不太了解语法,所以我不知道我做错了什么。也许有人可以帮助我。 提前致谢。

【问题讨论】:

  • 你能分享你的代码吗?

标签: javascript php wordpress function


【解决方案1】:

嗯,试试这个

add_filter("the_content", "my_content_modification");
function my_content_modification($content) {
  $post_type = get_post_type();
  $post_type_to_check = "MY_POST_TYPE";

  if ($post_type == $post_type_to_check) {
    $content = preg_replace('/<img(.*?)>/', '<div class="my-div"><img$1/></div>', $content);
  }

  return $content;
}

【讨论】:

  • 太棒了!不客气。
【解决方案2】:

如果有人也需要它,我刚刚添加了 img 的类。再次感谢乔丹·卡特。

add_filter("the_content", "my_content_modification");
function my_content_modification($content) {
  $post_type = get_post_type();
  $post_type_to_check = "MY_POST_TYPE";

  if ($post_type == $post_type_to_check) {
    $content = preg_replace('/<img(.*?)>/', '<div class="MY_DIV"><img class="MY_IMG" $1/></div>', $content);
  }

  return $content;
}

【讨论】:

  • 您可能希望将“$1”直接放在结尾引号“MY_IMG”之后。 $1 显示“(.*?)”部分中的所有内容,表示 之间的 img 标签中的所有内容。所以我认为通过添加该空间,您在技术上添加了一个额外的空间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 2018-02-23
  • 2014-11-02
  • 2015-03-15
  • 2017-06-02
  • 2015-11-20
相关资源
最近更新 更多