【问题标题】:How to get the image links from Gutenberg block gallery and add them as html data attributes to a button in wordpress如何从 Gutenberg 块库中获取图像链接并将它们作为 html 数据属性添加到 wordpress 中的按钮
【发布时间】:2022-01-21 18:38:53
【问题描述】:

我在帖子中使用了古腾堡画廊块,我正在尝试创建一个按钮,其中包含画廊块中的所有图像 id 作为 html 数据属性,这样以后当我将内容输出到页面时,我可以可以使用 javascript 访问这些 ID。基本上我正在尝试为自定义帖子类型创建灯箱功能。

问题是我无法访问古腾堡画廊块数据。

这是我的代码

while ($custom_post_type->have_posts()) {
    $custom_post_type->the_post();
    $gallery = get_post_gallery(get_the_id(), false);
    $ids = explode(",", $gallery['ids']);
}

这是带有 html 数据属性的按钮

<button class="gallery" 
<?php 
for ($i = 0; $i < count($ids); $i++) {
  $img_link = wp_get_attachment_image_url($ids[$i], 'full');
  echo "data-img-" . $i . " = " . $img_link . " ";
}?>
>
Light-box
</button>

但它不起作用,$ids 是空的。它打印出这个

<button class="gallery">Light-box</button>

感谢您的帮助!

编辑

我在帖子页面上使用 wordpress 块,我不太确定它们是如何生成的,但它们开箱即用。

【问题讨论】:

  • 这真的取决于你如何创建你的古腾堡块。您能否详细解释一下您是如何创建区块的?
  • 嗨@Ruvee 感谢您的回复,请参阅我的问题的编辑部分。

标签: php wordpress custom-wordpress-pages wordpress-gutenberg gutenberg-blocks


【解决方案1】:

“不行,$ids 是空的。”

该块是默认的 wordpress 块之一,也就是“核心块”。为了访问其数据,您需要使用parse_blocks 函数而不是get_post_gallery。这就是为什么你的变量是空的。


因此,获得所需内容的整体工作流程是:

  1. 使用has_block函数检查您的帖子是否有任何块。 has_blockDocs
  2. 如果是,则使用parse_blocks 函数获取所有块(包括画廊块)。 parse_blocksDocs
  3. parse_blocks 将返回您帖子中使用的所有块的数组,因此请遍历它们并查看哪个称为 "core/gallery"
  4. "core/gallery" 块包含您在管理面板中添加的每个图像的 "attributes""ids"
  5. 获得"ids" 后,您应该能够使用wp_get_attachment_image_url 函数创建自定义按钮和图像链接。 wp_get_attachment_image_urlDocs

作为 POC:

请看以下代码:

if (has_block("gallery", get_the_content())) 
{
  $post_blocks = parse_blocks(get_the_content());
  foreach ($post_blocks as $post_block) 
  {
    if ("core/gallery" == $post_block["blockName"]) 
    {
      $ids = $post_block["attrs"]["ids"];
    }
  }
}

这是按钮:

<button class="gallery" 
<?php
for ($i = 0; $i < count($ids); $i++) {
  $img_link = wp_get_attachment_image_url($ids[$i], "full");
  echo "data-img-" . $i . " = " . $img_link . " ";
}
?>
>
Light Box 
</button>

哪个会返回:

注意:

  • 我使用了get_the_content 函数,假设您根据您在问题中提供的代码处于循环中。如果您不在循环中,或者您需要在循环之外使用代码,您可以改用global $post; $post-&gt;post_content;

这个答案已经在 wordpress 5.8 上测试过并且有效。

【讨论】:

  • 把我从假期的挫折中解救出来,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多