Support

Account

Home Forums Front-end Issues Chechbox not working in foreach

Helping

Chechbox not working in foreach

  • Hello! I’m new to ACF and PHP / WordPress. I’m trying to get a checkbox value shown on my wordpress site, but I’m getting the error message “in_array() expects parameter 2 to be array..”

    This is my code:
    `<?php if(have_posts()) : ?>
    <?php while(have_posts()) : the_post(); ?>
    <?php
    $current_date =””;
    $count_posts = wp_count_posts();
    $nextpost = 0;
    $published_posts = $count_posts->publish;
    $myposts = get_posts(array(‘posts_per_page’=>$published_posts));
    foreach($myposts as $post) :
    $nextpost++;
    setup_postdata($post);
    $date = get_the_date(“F Y”);
    if($current_date!=$date):
    if($nextpost>1): ?>
    <?php endif; ?>
    <?php endif; ?>
    “>
    <img class=”all <?php $selected = get_field(‘type’);

    if( in_array(‘web’, $selected) ) {

    echo ‘web’;
    } ?>” />


    <?php endforeach; wp_reset_postdata(); ?>
    <?php endwhile; ?>
    <?php endif; ?>

  • Hi @unmatched

    It’s possible that the “type” field doesn’t have value, so get_field() will returns an empty string while in_array() needs an array for the second parameter, not an empty string.

    I think you can check if it has a value or not first like this:

    $selected = get_field('type');
    if($selected){
        if( in_array('web', $selected) ) {
            echo 'web';
        }
    }

    I hope this helps.

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

The topic ‘Chechbox not working in foreach’ is closed to new replies.