Support

Account

Home Forums Front-end Issues Calling image with a Select Field Type

Solving

Calling image with a Select Field Type

  • I created a custom Select Field Type for Attachments; the label is Image Category, the name is image_category and the type is select.

    In that custom field label I have 3 choices:
    banner_advert : Banner Advert
    footer_advert : Footer Advert
    content_advert : Content Advert

    What I would like to do around the site is echo the images that are tagged with that field label; I was trying to do this with $get_field() but am not having much success.

    For example, I would like to display 1 image which is tagged with banner_advert (there could be 2 or 4 that have the tag, so it should show a random one each time). Does anyone have any suggestion for this or know of a resource i could follow?
    I was thinking something like:

    if( get_field('image_category') == 'banner_advert' ) {
        	echo wp_get_attachment_image( get_the_ID(), 'full');
    }
  • The field you are trying to show is on the attachments. Using get_field where you are using it is trying to get the field from the current post.

    You need to query the attachments and get the post with the value. This will get a random attachment post.

    
    $args = array(
      'post_type' => 'attachment',
      'orderby' => 'rand',
      'posts+per_page' => 1,
      'meta_query' => array {
         array (
           'key' => 'image_category',
           'value' => 'banner_advert'
         )
      )
    );
    $my_query = new WP_Query($args);
    
  • Hello, you can solve your problem by calling get_field query for any image. I have used the same query in my own code. It is successful! You should also this once.

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

The topic ‘Calling image with a Select Field Type’ is closed to new replies.