• Resolved squasher

    (@squasher)


    Hi,

    I’ve created a shortcode to get the right data from the database. But I’m doing something wrong as I only get the last result instead of every result.

    This is my code:

    function holidaydata_func( $atts ) {
    	$a = shortcode_atts( array(
    		'country' => '',
    		'year' => '',
    	), $atts );
            $country = $a['country'];
            $year = $a['year'];
            
            global $wpdb;
            $tablename = 'table_name';
            $data = $wpdb->get_results($wpdb->prepare("SELECT country, country_eng, name_eng, week, remark, startdate FROM <code>$tablename</code> WHERE country = %s AND year LIKE %d ORDER BY startdate", $country, $year));
            $outputstart = '<table>';
            foreach ($data as $item) 
                {
                    $output = '<tr><td>'.$item->name_eng.'</td></tr>';
                }
            $outputend = '</table>';    
            
            return $outputstart . $output . $outputend;
    }
    add_shortcode( 'holidaydata', 'holidaydata_func' );

    So, this only results in one table row, instead of the multiple ones I should get.

    What am I doing wrong here?

    Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Correct the code as below:

     foreach ($data as $item) 
    {
     $output .= '<tr><td>'.$item->name_eng.'</td></tr>';
    
    }

    You need to append your $output with previous results with “.=” instead of “=”.

    • This reply was modified 5 years, 6 months ago by vigneshv01. Reason: updated notify via email
    Thread Starter squasher

    (@squasher)

    That was simple… it works now. 🙂

    Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Shortcode only outputs last result instead of every result’ is closed to new replies.