WordPress不用插件实现多张特色图片/缩略图Featured Images
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任何主题发布文章时,都可以设置单张特色图片,以便博客页面和列表页面调用,而对于想要在发布文章时,同时发布多个特色图片到文章页的效果,比如很多用WordPress做外贸电商站的,需要做产品信息,那可以采取如下方法。
- 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);
- ?>
-
- [url=###]" style="width:100%;" alt="">[/url]
-
-
- <input type="hidden" name="" id="" value="">
-
-
- 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, '');
- }
- }
- }
- }
复制代码 发布页效果演示
页面调用这些特色图片代码参考
- $image_id = get_post_meta( get_the_ID(), 'featured_image_2', true);
- echo wp_get_attachment_image($image_id,'full');
复制代码
需要实现swiper效果的可以自己将图片链接写进模板当中。

|