• I have some code, which is currently working correctly in my content templates, that I wish to put into a shortcode to use on the home page. Problem is, it just displays the word ‘Array’ on my page.
    Here is the code:

    function cat_posts_function($atts){
       extract(shortcode_atts(array(
    	  'cat' => 2
       ), $atts));
       	global $wpdb;
    	$querystr = $wpdb->get_results
    	("
    		SELECT wposts.*
    		FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    		WHERE wposts.ID = wpostmeta.post_id
    		AND wpostmeta.meta_key  = 'product_name'
    		AND wposts.post_type = 'post'
    		AND ID IN ( SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = '$cat' )
    		GROUP BY wpostmeta.meta_value
    	");
    	$pageposts = $wpdb->get_results($querystr, OBJECT);
    
    	 	 if ($pageposts):
    			global $post;
    			foreach ($pageposts as $post):
    			setup_postdata($post);
    			'<a href="'.get_permalink().'"><img class="th_list" src="'.site_url().'/images/'.get_field("product_code").'.jpg" /></a>';
    			endforeach;
    			wp_reset_postdata();
    		endif;
    	return $pageposts;
    }
    add_shortcode( 'cat_posts', 'cat_posts_function' );

    Does anyone know where I’ve gone wrong?
    Thanks

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    In your $pageposts foreach loop you’re not accumulating the link/image HTML into a variable. THAT is the variable you should return, not $pageposts.

    Thread Starter lolo23

    (@lolo23)

    Thank you, I’m not sure how to fix that though?!

    Moderator bcworkz

    (@bcworkz)

    $html='';
      if ($pageposts):
        global $post;
        foreach ($pageposts as $post):
          setup_postdata($post);
          $html .= '<a href="'.get_permalink().'"><img class="th_list" src="'.site_url().'/images/'.get_field("product_code").'.jpg" /></a>';
        endforeach;
        wp_reset_postdata();
      endif;
    return $html;
    Thread Starter lolo23

    (@lolo23)

    Thanks – makes sense. It has got rid of “Array” appearing, but now displays nothing at all!

    Moderator bcworkz

    (@bcworkz)

    Either there’s a PHP error somewhere or the query is not returning anything. I think I see the problem though. Nesting PHP statement (): endstatement; formats have never worked for me, try using the {} format instead with foreach:

    foreach ($pageposts as $post){
          setup_postdata($post);
          $html .= '<a href="'.get_permalink().'"><img class="th_list" src="'.site_url().'/images/'.get_field("product_code").'.jpg" /></a>';
        }

    If you still have trouble, be sure WP_DEBUG is defined as true in wp-config.php so you see any error messages.

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘Problem with custom shortcode using mysql query’ is closed to new replies.