php 根据帖子类型更改WordPress图像属性。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 根据帖子类型更改WordPress图像属性。相关的知识,希望对你有一定的参考价值。

<?php
/**
 * Filter image attributes if the attachment parent post is woocommerce product then change its
 * image attributes as desired.
 *
 * @param array        $attr       Attributes for the image markup.
 * @param WP_Post      $attachment Image attachment post.
 * @param string|array $size       Requested size. Image size or array of width and height values
 *                                 (in that order). Default 'thumbnail'.
 * @return array       $image      Modified Image attributes
 */
function mxc_change_woocommerce_image_srcset( $attr, $attachment, $size ) {
	global $post;
	$attachment_id         = $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 ( 'product' === get_post_type( $attachment->post_parent ) ) {
		// Iterate to the current post attachment.
		foreach ( get_attached_media( 'image', $attachment->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( $attr['src'], $upload_dir['baseurl'] ) || false !== strpos( $attr['srcset'], $upload_dir['baseurl'] ) ) {
					// Remove base url to the image src.
					$attr['src'] = str_replace( $upload_dir['baseurl'], $new_image_baseurl_src, $attr['src'] );
					$attr['srcset'] = str_replace( $upload_dir['baseurl'], $new_image_baseurl_src, $attr['srcset'] );
					if ( $remove_subdir ) {
						$attr['src'] = str_replace( $upload_dir['subdir'], $new_image_subdir_src, $attr['src'] );
						$attr['srcset'] = str_replace( $upload_dir['subdir'], $new_image_subdir_src, $attr['srcset'] );
					}
				}
			}
		}
	}
	return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'mxc_change_woocommerce_image_srcset', 10, 3 );

以上是关于php 根据帖子类型更改WordPress图像属性。的主要内容,如果未能解决你的问题,请参考以下文章

PHP 获取Wordpress帖子的主要图像

使用下拉菜单动态过滤 Wordpress 帖子(使用 php 和 ajax)

PHP wordpress - 从附加到帖子的图像自动创建Greybox图像集

PHP 显示WordPress帖子的第一个图像附件

PHP Wordpress - 如果没有图像设置,则显示带有帖子的特色图像或默认图像

PHP 使用帖子附件的Wordpress图像库短代码