Search code examples
phpwordpressshortcode

How to return scandir output inside Wordpress short code?


I made WP shortcode to list all files inside specific directory in order to return/echo the result between worpress visual composer tab shortcode [tab title="TEST ME"]SCANDIRE OUTPUT[/tab]

And this is my functions code:

/* Start of SC Scan files */
function xs_sc_specsheets() {
        $files = scandir('./documents/FD30/5_Hardware/Concort/Specsheets');
        sort($files); // this does the sorting
        foreach($files as $file){
                if($file == ".." || $file == ".") continue; //Skip parent directory links
                $xsresult = '<div class="wpb_wrapper"> <div class="column one-third"> <a class=" button  button_full_width button_size_2 button_js" href="/documents/FD30/5_Hardware/Concort/Specsheets/'.$file.'"><span class="button_label">'.$file.'</span></a> </div></div>' ;
        }
        return do_shortcode('[tab title="TEST ME"]' . $xsresult . '[/tab]');
}

if (function_exists('xs_sc_specsheets')) {
    add_shortcode( 'sc_specsheets', 'xs_sc_specsheets');
}
/* End of SC Scan files */

The results appeared on my WP content in proper tab position with one problem tha only one file show from the total files.

Where is the issue in my code?


Solution

  • In each step of the loop you reset final return xsresult variable. Try "$xsresult.=" instead of "xsresult=". Here it is

    /* Start of SC Scan files */
    function xs_sc_specsheets() {
            $files = scandir('./documents/FD30/5_Hardware/Concort/Specsheets');
            sort($files); // this does the sorting
            $xsresult='';
            foreach($files as $file){
                    if($file == ".." || $file == ".") continue; //Skip parent directory links
                    $xsresult.= '<div class="wpb_wrapper"> <div class="column one-third"> <a class=" button  button_full_width button_size_2 button_js" href="/documents/FD30/5_Hardware/Concort/Specsheets/'.$file.'"><span class="button_label">'.$file.'</span></a> </div></div>' ;
            }
            return do_shortcode('[tab title="TEST ME"]' . $xsresult . '[/tab]');
    }
    
    if (function_exists('xs_sc_specsheets')) {
        add_shortcode( 'sc_specsheets', 'xs_sc_specsheets');
    }
    /* End of SC Scan files */