php 如果附件父帖是woocommerce产品,则过滤图像src,然后根据需要更改其* image src

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 如果附件父帖是woocommerce产品,则过滤图像src,然后根据需要更改其* image src相关的知识,希望对你有一定的参考价值。

<?php

/**
 * Filter image src if the attachment parent post is woocommerce product then change its
 * image src as desired.
 *
 * @param array|false $image
 * @param int $attachment_id
 * @param string|array $size
 * @param bool $icon
 * @return void
 */
function mxc_change_woocommerce_image_src( $image, $attachment_id, $size, $icon ) {
	$image_object = get_post( $attachment_id );
	$upload_dir            = wp_upload_dir();
	$remove_subdir         = false; // IMPORTANT: Change to false if you want subdir to remain in the image src / srcset.
	$new_image_baseurl_src = 'https://desired-url.com/wp-content/uploads'; // IMPORTANT: Change this to the desired image url.
	$new_image_subdir_src  = ''; // Example Value '/2018/05'.

	if ( $image ) {
		if ( 'product' === get_post_type( $image_object->post_parent ) ) {
			// Iterate to the current post attachment.
			foreach ( get_attached_media( 'image', $image_object->post_parent ) as $image_attachment ) {
				// if the image is attached to a product post type change its url to desired url.
				if ( (int) $attachment_id === $image_attachment->ID ) {
					// Make sure that we have b$upload_dir['baseurl'] in the image src / srcset.
					if ( false !== strpos( $image[0], $upload_dir['baseurl'] ) ) {
						// Remove base url to the image src.
						$image[0] = str_replace( $upload_dir['baseurl'], $new_image_baseurl_src, $image[0] );
						if ( $remove_subdir ) {
							$image[0] = str_replace( $upload_dir['subdir'], $new_image_subdir_src, $image[0] );
						}
					}
				}
			}
		}
	}

	return $image;
}
add_filter( 'wp_get_attachment_image_src', 'mxc_change_woocommerce_image_src', 10, 4 );
// apply_filters( 'wp_get_attachment_image_src', array|false $image, int $attachment_id, string|array $size, bool $icon );
// https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_src/

以上是关于php 如果附件父帖是woocommerce产品,则过滤图像src,然后根据需要更改其* image src的主要内容,如果未能解决你的问题,请参考以下文章

php 隐藏WooCommerce中的产品类别。如果要在商店页面上隐藏产品类别计数,则只需将此代码添加到t

Woocommerce 如果产品有加售在产品列表中显示徽章

WooCommerce:如何在循环外显示销售产品

php 将自定义字段添加到WooCommerce产品#woocommerce #custom-fields

php 为Betheme改变WooCommerce单一产品页面位置,用于XL WooCommerce销售触发插件

如何从functions.php中的简码挂钩中排除产品类别ID - WooCommerce