WordPress不用插件实现多张特色图片/缩略图Featured Images

本站所有文章均为博主人工写作,绝无AI辅助成分,请放心参阅。

WordPress的文章、页面或者自定义文章类型开启特色图片,通过注册这个类型时,在support中添加参数“thumbnail”实现,比如:

register_post_type('My CPT', array(
	'label' => 'my_cpt',
	'description' => '',
	'public' => true,
	'show_ui' => true,
	'show_in_menu' => true,
	'capability_type' => 'post',
	'hierarchical' => false,
	'rewrite' => array('slug' => 'product'),
	'query_var' => true,
	'supports' => array('title','editor','thumbnail') //这里有了thumbnail就能为my_cpt这个类型添加缩略图
	)
);

这个缩略图有没有可能变成多张呢?比如这样:

查了老半天,WordPress本身并没有提供多张特色图片的API,但这个功能完全可以通过自定义字段实现。本文即是这个原理,不多废话,上代码:

<?php
add_action( 'after_setup_theme', 'brain1981_featured_img_setup' );
function brain1981_featured_img_setup(){
	add_action( 'add_meta_boxes', 'brain1981_feature_img_meta_box' );
	add_action( 'save_post', 'brain1981_feature_img_meta_box_save' );
}
 
function brain1981_feature_img_meta_box(){
	//$post_types = array('post','page');//给原生的文章和页面开启额外缩略图
	$post_types = array('my_cpt');
	foreach($post_types as $post_type){
		add_meta_box('brain1981_feature_img_meta_box', __( 'More Product Images'), 'brain1981_feature_img_meta_box_cont', $post_type, 'side','low');
	}
}
 
function brain1981_feature_img_meta_box_cont($post){
	//以下这个数组可以任意扩展,比如featured_image_4,5,6...
	$meta_keys = array('featured_image_2','featured_image_3');
	foreach($meta_keys as $meta_key){
		$image_meta_val=get_post_meta( $post->ID, $meta_key, true);
		?>
		<div class="cpm_image_wrapper" id="<?php echo $meta_key; ?>_wrapper" style="margin-bottom:28px;" >
			<a href="###" class="cpm_addimage cpm_addimage_img" data-metakay="<?php echo $meta_key; ?>" style="display: <?php echo ($image_meta_val!=''?'block':'none'); ?>">
				<img src="<?php echo ($image_meta_val!=''?wp_get_attachment_image_src( $image_meta_val, "full")[0]:''); ?>" style="width:100%;" alt="">
			</a>
			<a href="###" class="cpm_removeimage" style="display: <?php echo ($image_meta_val!=''?'block':'none'); ?>" data-metakay="<?php echo $meta_key; ?>"><?php _e('Remove featured image'); ?></a>
			<a href="###" class="cpm_addimage" style="display: <?php echo ($image_meta_val!=''?'none':'block'); ?>" data-metakay="<?php echo $meta_key; ?>"><?php _e('Set featured image'); ?></a>
			<input type="hidden" name="<?php echo $meta_key; ?>" id="<?php echo $meta_key; ?>" value="<?php echo $image_meta_val; ?>" />
		</div>
	<?php } ?>
<script>
jQuery(function(){
	jQuery(".cpm_addimage").on("click",function(){
		var key = jQuery(this).data("metakay");
		cpm_meta_box_add_img(key);
	});
	function cpm_meta_box_add_img(key){
		var $wrapper = jQuery('#'+key+'_wrapper');
 
		cpm_meta_box_img_uploader = wp.media.frames.file_frame = wp.media({
			title: '<?php _e('select image','kais'); ?>',
			button: {
				text: '<?php _e('select image','kais'); ?>'
			},
			multiple: false
		});
		cpm_meta_box_img_uploader.on('select', function() {
			var attachment = cpm_meta_box_img_uploader.state().get('selection').first().toJSON();
			var img_url = attachment['url'];
			var img_id = attachment['id'];
			$wrapper.find('input#'+key).val(img_id);
			$wrapper.find('img').attr('src',img_url);
			$wrapper.find('a.cpm_removeimage').show();
			$wrapper.find('a.cpm_addimage').hide();
			$wrapper.find('.cpm_addimage_img').show();
 
		});
		cpm_meta_box_img_uploader.on('open', function(){
			var selection = cpm_meta_box_img_uploader.state().get('selection');
			var selected = $wrapper.find('input#'+key).val();
			if(selected){
			    selection.add(wp.media.attachment(selected));
			}
		});
		cpm_meta_box_img_uploader.open();
		return false;
	}
 
	jQuery(".cpm_removeimage").on("click",function(){
		var key = jQuery(this).data("metakay");
		cpm_meta_box_remove_img(key);
	});
	function cpm_meta_box_remove_img(key){
		var $wrapper = jQuery('#'+key+'_wrapper');
		$wrapper.find('input#'+key).val('');
		$wrapper.find('a.cpm_removeimage').hide();
		$wrapper.find('a.cpm_addimage').show();
		$wrapper.find('.cpm_addimage_img').hide();
		return false;
	}
});	
</script>
	<?php
	wp_nonce_field( 'brain1981_feature_img_meta_box', 'brain1981_feature_img_meta_box_nonce' );
}
 
function brain1981_feature_img_meta_box_save($post_id){
	if ( ! current_user_can( 'edit_posts', $post_id ) ){ return 'not permitted'; }
	if (isset( $_POST['brain1981_feature_img_meta_box_nonce'] ) && wp_verify_nonce($_POST['brain1981_feature_img_meta_box_nonce'],'brain1981_feature_img_meta_box' )){
		//以下这个数组可以任意扩展,比如featured_image_4,5,6...,但必须和brain1981_feature_img_meta_box_cont函数中一致
		$meta_keys = array('featured_image_2','featured_image_3');
		foreach($meta_keys as $meta_key){
		    if(isset($_POST[$meta_key]) && intval($_POST[$meta_key])!=''){
		    	update_post_meta( $post_id, $meta_key, intval($_POST[$meta_key]));
		    }else{
		    	update_post_meta( $post_id, $meta_key, '');
		    }
		}
	}
}

以下CSS非必须,是为了让后台这张图片在透明的时候能显示网格,和WP官方UI一致:

.cpm_image_wrapper img{
	background-image:linear-gradient(45deg,#c3c4c7 25%,transparent 25%,transparent 75%,#c3c4c7 75%,#c3c4c7),linear-gradient(45deg,#c3c4c7 25%,transparent 25%,transparent 75%,#c3c4c7 75%,#c3c4c7);
	background-position: 0 0,10px 10px;
	background-size: 20px 20px;
}
?>

在页面调用这些新增的特色图片:

$image_id = get_post_meta( get_the_ID(), 'featured_image_2', true);
echo wp_get_attachment_image($image_id,'full');

以上代码即是通过给featured_image_2、featured_image_3这些自定义字段存储上传图片的id,实现多张自定义特色图片。WP本身的自定义图片其实也是这个原理,只是变量名称不同,并且有几个内部的方法可以调用;而调用这些自定义的特色图片则只能通过通用的方法。其实我更喜欢用这些通用方法调用任何附件图片,比唯一那张特色图片独有的方法要普适好记。

本站所有文章均为原创,欢迎转载,请注明文章出处:https://blog.brain1981.com/2378.html。百度和各类采集站皆不可信,搜索请谨慎鉴别。技术类文章一般都有时效性,本人习惯不定期对自己的博文进行修正和更新,因此请访问出处以查看本文的最新版本。

关注我们的微信公众号-JennyStudio 本站记录了近几年的工作中遇到的一些技术问题和解决过程,“作品集”还收录了本人的大部分作品展示。除了本博客外,我们的工作室网站 – JennyStudio,内有更多作品回顾和展示。
您也可以扫描左边的二维码,关注我们的微信公众号,在微信上查看我们的案例。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注