Support

Account

Home Forums Front-end Issues Post object with array_rand

Unread

Post object with array_rand

  • Hello, i want to pick 2 random ids from object and show only them, i’ve managed to hide them via jquery, but i dont want to load them at all

    php
    $post_objects = get_field( ‘navigacija’, ‘option’ );
    if ( $post_objects ): ?>
    <?php $niz = [];
    ?>
    <?php $rand_keys = array_rand( $post_objects );
    ?>

    <?php foreach ( $post_objects as $post ): // variable must be called $post (IMPORTANT) ?>
    <?php setup_postdata( $post ); ?>
    <?php $niz[] = $post->ID;?>
    <div class=”hidden-{{ $post->ID }} card align-items-center”>
    <img class=”card-img-top img-fluid”
    src=”{{ the_field(‘slika_za_navigaciju’,$post->ID) }}” alt=””>
    <div class=”card-body p-0″>
    <div class=”row”>
    <div class=”col-lg-12 col-xl-12″>
    <h5 class=”card-title mt-5″>{{ the_field(‘naslov_za_navigaciju’,$post->ID) }}</h5>
    </div>
    <div class=”col-lg-12 col-xl-12″>
    <div class=”row”>
    <div class=”col-lg-6 col-xl-6 px-lg-1 cardmar”>
    <span class=”cena prvi”>{{ the_field(‘cena’,$post->ID) }}€</span>
    <span
    class=”card-text”>{{ the_field(‘naziv_akcije_za_navigaciju’,$post->ID) }} </span>
    </div>
    <div class=”col-lg-6 col-xl-6 hov”>
    ID) }}”
    class=”btn btn-outline-primary prvi more”>{{ the_field(‘pogledaj’,$post->ID) }}

    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    <?php endforeach; ?>
    <?php
    $input = $niz;
    $rand_keys = array_rand( $input, 2 );
    $input[ $rand_keys[0] ] . “\n”;
    $input[ $rand_keys[1] ] . “\n”;
    ?>
    <script type=”text/javascript”>

    function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle…
    while (0 !== currentIndex) {

    // Pick a remaining element…
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
    }

    return array;
    }

    var items = <?php
    echo json_encode( $niz );
    ?>;
    </script>
    <?php wp_reset_postdata(); // IMPORTANT – reset the $post object so the rest of the page works correctly ?>
    <?php endif;
    ?>

    <script type=”text/javascript”>
    // Used like so
    item = shuffle(items);
    console.log(item);
    console.log(item[0]);
    console.log(item[1]);

    var el1 = item[0];
    var el2 = item[1];

    jQuery(‘.hidden-‘ + el1).hide();
    jQuery(‘.hidden-‘ + el2).hide();

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.