如何获取产品图片或任何帖子/产品页面的特色图片的绝对路径?
我试着喜欢这个:
$product = wc_get_product( $postid);
$product->get_image('large'); //output like <img src="url of image" alt="xyz"/>
然后,我尝试使用php-prag_match函数从image标签(来自上面的输出)中获取src路径。然后按域名url进行拆分,得到剩余路径并创建绝对路径。
$filename = getcwd().'/wp-content/uploads/2016/02/xyz.jpg';
这对我来说很有效,但它看起来很复杂,很有管理。请告诉我有没有最简单的方法?
$feat_image = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );
echo esc_url( $feat_image );
- https://wordpress.org/support/topic/getting-a-post-featured-image-url
- https://wordpress.org/support/topic/retrieveing-featured-image-url
- https://developer.wordpress.org/reference/functions/wp_get_attachment_url/
为了获得系统路径,Konstantin Kovshenin建议如下:
$url = wp_get_attachment_url( $post_ID );
$uploads = wp_upload_dir();
$file_path = str_replace( $uploads['baseurl'], $uploads['basedir'], $url );
- https://kovshenin.com/2011/attachments-filename-and-directory-in-wordpress/
- https://developer.wordpress.org/reference/functions/wp_upload_dir/