Fahad Sohail
Fahad Sohail

Reputation: 1836

PHP Repeating Results in Loop

Hello guys so I have this simple problem and I need help solving it. I am creating a simple PHP shortcode for WordPress where it takes 3 inputs audio text and totalposts. I was able to create the layout of the shortcode but I dont know why but its repeating the results in while loop.

Below is the code:

function header_custom_box($atts) {

    $atts = shortcode_atts( array( 'audio' => '', 'text' => '', 'totalposts' => '3'), $atts, 'header-custom-box' );

    $audioFiles = explode( ",", $atts['audio'] ); 
    $descText = explode( ",", $atts['text'] );

    $postCount = $atts['totalposts'];
    $posts = array();
    $audioArray = array();
    $imagesArray = array();
    $textArray = array();
    $buf = '';
    $counter = 0;

    foreach ($audioFiles as $audioFile) {
        $attr = array(
        'src'      => $audioFile,
        'loop'     => '',
        'autoplay' => '',
        'preload' => 'none'
        );
        $audioArray[] = wp_audio_shortcode( $attr );
    }

    foreach ($descText as $desc) {
        $textArray[]  = $desc;
    }

    while ($counter < $postCount) { 
        $buf .= '<div class="header-tab-box">';
        $buf .= '<div class="audio-text"><h2>Your Daily Audio:</h2> <br/>';
        $buf .= $textArray[$counter];
        $buf .= '</div>';
        $buf .= '<div class="audio-player">';
        $buf .= $audioArray[$counter];
        $buf .= '</div>';
        $buf .= '</div>';
        $posts[$counter] = $buf;
        $counter++;
    }
    return $posts;

}
add_shortcode( 'header-custom-box', 'header_custom_box' );

Also, it displays result when I var_dump($posts) but if I return $post it says Array

There is one more thing I need to apply in this shortcode, which is delay in every post, like it should change to the next post after every 24 to 58 hours.

Thanks in advance.

Upvotes: 0

Views: 139

Answers (1)

szapio
szapio

Reputation: 1008

It's repeating because you don't reset your $buf variable in each iteration so in first iteration $buf = "firstRow", second iteration $buf = "firstRowSecondRow"... And this prints you Array, because you returns array $posts contains pieces of html. If You want to print all pieces together just use implode function

 while ($counter < $postCount) { 
        $buf = ""; // make this empty in each iteration
        $buf .= '<div class="header-tab-box">';
        $buf .= '<div class="audio-text"><h2>Your Daily Audio:</h2> <br/>';
        $buf .= $textArray[$counter];
        $buf .= '</div>';
        $buf .= '<div class="audio-player">';
        $buf .= $audioArray[$counter];
        $buf .= '</div>';
        $buf .= '</div>';
        $posts[$counter] = $buf;
        $counter++;
    }
    return implode('',$posts);

Upvotes: 1

Related Questions