【问题标题】:How to get image title and description from Wordpress Media如何从 Wordpress Media 获取图像标题和描述
【发布时间】:2021-11-02 14:39:44
【问题描述】:

我有一个产品页面,您可以在其中创建自己的产品,您可以根据每个选择更改显示的图像

一旦用户点击按钮,我想使用简码从 Wordpress 的媒体部分获取当前显示图像的标题和描述。

现在我发现很多帖子都有这个代码(你必须插入functions.php

function wp_get_attachment( $attachment_id ) {

    $attachment = get_post( $attachment_id );
    return array(
        'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
        'caption' => $attachment->post_excerpt,
        'description' => $attachment->post_content,
        'href' => get_permalink( $attachment->ID ),
        'src' => $attachment->guid,
        'title' => $attachment->post_title
    );
}

然后用这段代码调用函数

$attachment_meta = wp_get_attachment($attachment_id);

编辑:我在这篇文章中找到了代码here

但由此收集的数据仅与产品页面有关(因此页面的标题和描述),而不是我要查找的数据。

我发现在页面上获取图片的 attachment_id 的唯一方法是使用这篇文章here 但它是手动完成的,我需要在简码中完成......

这是完整的代码

add_shortcode( 'afficher_produits_devis2', function(){
    $attachment_meta = wp_get_attachment($attachment_id);
    echo $attachment_meta['caption'];
} );

function wp_get_attachment( $attachment_id ) {

    $attachment = get_post( $attachment_id );
    return array(
        'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
        'caption' => $attachment->post_excerpt,
        'description' => $attachment->post_content,
        'href' => get_permalink( $attachment->ID ),
        'src' => $attachment->guid,
        'title' => $attachment->post_title
    );
}

编辑 2

我可能已经通过@Ruvee 的this 帖子找到了解决这个难题的方法,但现在我必须找到一种方法来解析页面的 html 并获取图像的 URL。

编辑 3

我发现为什么我只能获取缩略图数据,结果是当我加载产品页面而不是单击按钮时直接激活了简码。所以它只激活一次,并且总是出现第一张图片(缩略图)。

我纠正了错误,现在它可以按我的意愿工作了 谢谢@Ruvee

【问题讨论】:

  • “但是这里收集的数据只是关于产品页面” - 那么$attachment_id包含的内容可能是该页面的帖子ID,而不是任何实际附件。但是您的问题缺乏上下文,您只向我们展示了该函数,但没有向我们展示您实际调用它的位置/参数。
  • 什么是 wp_get_attachment ?你从哪里得到这个 $attachment_id ?您分享了与您的问题无关的代码。
  • 没有理由为此使用任何特殊功能。附件还是posts,你可以使用get_post($id),它会返回你要找的所有数据——$id是图片id。
  • 我已经编辑了问题@CBroe,你可以找到源代码。另外,我没有找到如何在后台手动获取图片的 attachment_id 的方法,所以是的,该函数可能使用了产品页面的 id

标签: php wordpress wordpress-theming shortcode custom-wordpress-pages


【解决方案1】:

“我得想办法解析页面的html,得到图片的URL。”

不,那没必要!就像我在this answer 中所说,在没有实际图像 url 的情况下获取元数据的第二种方法是使用id of the image。你可以通过get_post_thumbnail_id函数得到id of the image

所以你的简码应该是这样的:

add_shortcode( 'afficher_produits_devis2', function(){
    global $post;
    $image_id = get_post_thumbnail_id($post->ID);
    $image_caption = get_post_field('post_excerpt', $image_id);
    echo $image_caption;
} );

【讨论】:

  • 但是那不是只取页面的缩略图吗?
  • 这取决于你想在哪里调用它。你没有提到任何细节。您也可以在 wordpress 循环中使用 et_post_thumbnail_id 函数。这个$image_id = get_post_thumbnail_id(get_the_id()); 会在不使用global $post; 的情况下做同样的事情。
  • 在您的产品页面中,您甚至不需要使用简码来完成这项任务!你让自己变得更难了。您可以连接到产品页面的查询,然后在我的回答中使用第二个解决方案。这很简单。
  • 是的,我知道,但是当我尝试这样做时,它只会获取原始缩略图的数据,而不是替代图像的数据
  • 发现我的错误!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 2017-09-24
相关资源
最近更新 更多