Friday, 12 June 2015

How to set different thumbnail sizes per custom post type?

Registers a new image size. This means WordPress will create a copy of the image with the specified dimensions when a new image is uploaded.
To set the default Featured Image (formerly Post Thumbnail) dimensions use: set_post_thumbnail_size().

Usage

<?php add_image_size$name$width$height$crop ); ?>

if you have multiple post types, maybe this will help
(not tested)(in the loop)

<?php
$post_type = get_post_type(); // get's the post type of a post in the loop
$args=array(
  'public'   => true,
  '_builtin' => false
);
$output = 'names'; // names or objects
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types($args,$output,$operator); // gets all post types you registered
$post_types = array_values($post_types); // makes it a numerically indexed array

if(in_array( $post_type, $post_types)){ // post is a custom post type -> show post type size thumbnail
  $custom_post_thumbnail = get_the_post_thumbnail($post->ID, $post_type.'-thumbnail');
  if($custom_post_thumbnail != ''){ // there is a custom post thumbnail size
    echo $custom_post_thumbnail;
  } else { // no custom post thumbnail size -> show normal thumbnail
    echo get_the_post_thumbnail($post->ID);
  }
} else { // show normal thumbnail for posts and pages
  echo get_the_post_thumbnail($post->ID);
}
?>


You still have to add the image sizes manually in your theme's functions.php

If you have custom post types review and movies:

add_image_size( 'review-thumbnail', 150, 200, true );
add_image_size( 'movies-thumbnail', 400, 9999 );


No comments:

Post a Comment

Popular Articles