• Resolved stabilimenta

    (@stabilimenta)


    I am creating a shortcode that returns various meta data depending on the shortcode attributes.
    The shortcode I have on my page looks something like this:
    [contactinfo include="name, title"]
    The function that creates the shortcode looks like this:

    function contactinfo_shortcode( $atts ) {
    	extract( shortcode_atts(
    		array(
    			'include' => 'all',
    		), $atts )
    	);
    
    	$output = "";
    	$value = array($include);
    	$value = explode(',', $include);
    	foreach ($value as $att_id) {
    		if ($att_id == 'name') {
    			if (get_option('stab_contact_name')) {
    				$output .= "<div class=\"name\">" . get_option('stab_contact_name') . "</div>\n";
    			}
    		}
    		elseif ($att_id == 'title') {
    			if (get_option('stab_contact_job_title')) {
    				$output .= "<div class=\"job-title\">" . get_option('stab_contact_job_title') . "</div>\n";
    			}
    		}
    	} // foreach
    
    	return $output;
    }
    add_shortcode( 'contactinfo', 'contactinfo_shortcode' );

    The problem that has me stumped is that the loop never makes it past the “name”.
    I tried it using a switch/case method, but that wasn’t allowing me to control the order of the data items being returned, for example if the shortcode was set [contactinfo include="title, name"] instead of [contactinfo include="name, title"].

    Can anyone advise me? Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter stabilimenta

    (@stabilimenta)

    BTW: if I do a print_r $value just before the foreach, I get this: Array ( [0] => name [1] => title )

    Thread Starter stabilimenta

    (@stabilimenta)

    AGGG!!!!!! As soon as I posted it I realized my mistake! There is a space after each item in the shortcode argument list! That was the error.

    Moderator bcworkz

    (@bcworkz)

    😀 Something about publicly expressing one’s issue causes about 10% of posters here to immediately see their own problem!

    FWIW, you can’t count on people using shortcodes to know not to use spaces. It may be better to accommodate a predictable blunder in code with something like $value = array_map('trim', $value);

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘if testing value of array value inside a foreach loop’ is closed to new replies.