Support

Account

Home Forums General Issues Use select field for the_post_thumbnail

Helping

Use select field for the_post_thumbnail

  • Hi Elliot,

    I want to give the user the option to choose between having a big thumbnail and a smaller thumbnail.

    So I created a select field with two options:

    big : big
    small : small

    In my functions I added two sizes:

    if ( function_exists( 'add_image_size' ) ) { 
    	add_image_size( 'big', 550, 9999 ); 
    	add_image_size( 'small', 300, 9999 );
    }

    In my code I want the the_post_thumbnail to use the select value as the size.

    $size = get_field('image_size');
    
    if ( has_post_thumbnail() ) { 
            the_post_thumbnail( '$size' ); 
    }

    I’m not certain if this is the correct way of doing this, it makes sense in my head but I don’t have much knowledge of php. My page.php code is below.

    <?php
    
    $args = array( 
    	'post_type' => 'post'
    );
    
    $size = get_field('image_size');
    
    $myposts = get_posts( $args );
    foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    
    	<li>
    		<?php 
        if ( has_post_thumbnail() ) { 
            the_post_thumbnail( '$size' ); 
        } 
    ?>
    	</li>
    
    <?php endforeach; 
    wp_reset_postdata();?>
  • Hi @stevenharris

    Close, but change:

    the_post_thumbnail( '$size' );

    to

    the_post_thumbnail( $size );

    Please be aware, that you have placed the $size = get_field('image_size'); OUTSIDE of your $myposts loop, so this value is not coming from the post itself, but from what ever the template file is querying.

    Thanks
    E

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Use select field for the_post_thumbnail’ is closed to new replies.