【发布时间】: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