• Hi. I’ve written a simple plugin that displays Business Names of users based on a zip code ($zip) that they have entered during registration. This information needs to be displayed to all.

    So I’m trying to display all business names with a zip code of “553031234”. The way I’ve written it is to get the user_id first for all businesses with that zip code. Then based on that I display the name of the business. I’m not very good at php and maybe there’s a better way to do it. If so, please help.

    The data is taken from the wp_usermeta table. I’m using a shortcode to display the output of the function. When I use echo, it works but the output is above my content. I want it below. When I use return, the output is below but it only displays one name and I know there are three.

    Here’s my code for both the shortcode and business name function.

    function list_business_info_register_shortcodes(){
       add_shortcode('list-business-info', 'list_business_info_function');
    }
    add_action( 'init', 'list_business_info_register_shortcodes');
    function list_business_info_function()
    {
    	$zip = "553031234";
    	$result = mysql_query("SELECT user_id FROM wp_usermeta WHERE meta_key='rpr_9-digit_zip_code' AND meta_value=$zip");
    	while ($row = mysql_fetch_array($result))
    	{
    		$userid = $row['user_id'];
    		$result2 = mysql_query("SELECT meta_value FROM wp_usermeta WHERE meta_key='rpr_business_name' AND user_id=$userid");
    		while ($row2 = mysql_fetch_array($result2))
    		{
    		$busname = $row2['meta_value'];
    		return $busname;
    		}
    	}
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    First, never echo content from a shortcode handler. Always accumulate content in a string and return the string.

    When PHP encounters a return; statement, any pending loops are canceled and the function is immediately terminated. This is why you only get one value.

    You should first initialize an empty collector before entering the loop. Such as $busname = '';.

    Then inside the loop, accumulate each value like so:
    $busname .= $row2['meta_value'] . ' ';

    Then, only outside the loop do you return $busname;.

    And another thing, do not use mysql_*() functions to access the WP database, it is inefficient. Instead use $wpdb methods, or if possible a new WP_Query object.

    Thread Starter DRandy

    (@drandy)

    Ok great. thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Plugin returns only one value but database has many’ is closed to new replies.