Search code examples
wordpressloopsforeachshortcode

WordPress Foreach showing only one result


I have following WP function and shortcode I wrote

function selected_inventory_products( $atts ) {
    extract( shortcode_atts( array(
        'brand' => '',
        'product' => '',
    ), $atts ) );

        global $wpdb;
        $inventory_products = $wpdb->get_results("SELECT * FROM wp_inventory, wp_inventory_images WHERE wp_inventory.inventory_id = wp_inventory_images.inventory_id and sort_order = 0 and inventory_manufacturer = '".$brand."'");

        foreach($inventory_products as $i_products){
        $return_string = '<div style="background: #F4F4F4; width: 100%;">';
        $return_string .= '<a href="http://www.devicemondo.com/products/item/'.$i_products->inventory_slug.'/">'.$i_products->inventory_name.'</a>';
        $return_string .= '</div>';
        }

        return $return_string;

}
add_shortcode( 'post_sidebar_products', 'selected_inventory_products' );

the problem is that it when I use shortcode [post_sidebar_products] inside my WP pages I only get 1 result even if there is more then 15? Any idea where I made a mistake?

Thanks for help


Solution

  • Ah! Just saw it. You are redefining $return_string each time inside the loop ! Because of the first line, where you have no dot before the equal sign. So replace this :

        $return_string = '<div style="background: #F4F4F4; width: 100%;">';
    

    with this :

        $return_string .= '<div style="background: #F4F4F4; width: 100%;">';