0

I'm trying to display meta content from a custom post type in a shortcode. I'd like to simply provide a post_id and be able to display all the meta content.

[my_shortcode post_id=""]

I'm new to PHP and writing shortcodes, this seems as though it should be fairly simple... I know the following is wrong:

function promotion_function($atts) {
extract(shortcode_atts(array(
    'promo_id' => '',
), $atts));
global $post;
$meta_values = get_post_custom($promo_id, 'product_desc');

$output = $meta_values;
return $output;
}
add_shortcode('promotion', 'promotion_function');

The above code gives me the string "Array" in my page.

I can't find an example of how to do this, any help would be greatly appreciated.

1

1 Answer 1

1

You cannot print an array directly. The most basic return value you could use is var_export( $meta_values, TRUE );.

This will create a text representation of the value.

Probably better is a little walker like

$output = '';

foreach( $meta_values as $key => $value )
    $output .= "$key = " . esc_html( end( $value ) ) . '<br />';

return $output;
7
  • Ay, thank you. I had tried something similar with no luck. This certainly helps. Interesting; now I get an array for each key's value. I was expecting one value. I fear I may be asking some very basic questions... Is there a codex link I should be referencing for this? I've already reviewed the get_post_meta codex page.. Thanks again.
    – lauren
    Commented Nov 11, 2013 at 23:44
  • @lauren See this explanation: wordpress.stackexchange.com/a/100699/73
    – fuxia
    Commented Nov 12, 2013 at 9:09
  • You rock. Thank you - I'll chew on that for a bit.
    – lauren
    Commented Nov 12, 2013 at 18:24
  • I'm still getting all of the keys displaying all of their values. I thought using 'true' would only display the first value. Here's my code: function promotion_function($atts) { extract(shortcode_atts(array( 'promo_id' => '', ), $atts)); $get_title = get_post_custom($promo_id, product_title', true); $title = esc_html( var_export( $get_title, TRUE ) ); return $title; } add_shortcode('promotion', 'promotion_function'); I apologise for my code block not being a code block; I'm finding the instructions for creating a code block in comments to be extremely unclear :/
    – lauren
    Commented Nov 12, 2013 at 20:31
  • 1
    Alright, here is what worked: $meta_values = get_post_custom($promo_id, 'product_title', true); echo $meta_values['product_title'][0];
    – lauren
    Commented Nov 15, 2013 at 2:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.