0

I am trying to get the variable passed in my shortcode so I can do a request with the id to a API.

The shortcode looks like this: [product id="2"]

In my function I want to do something with the "2".

Code so far:

function getSingleProduct( $attr ) {
    shortcode_atts( [
      'id' => '0',
    ], $attr  );

    // Do someting with the "2".
    do_request( 'GET', get_api_url() . 'api/product/' . "2" ); // This "2" comes from the shortcode
}

add_shortcode( 'product', 'getSingleProduct' );
  • Where you have // Do something with the "2", just do something with it, I think I don't understand your question. Can you try to explain the problem deeply? – cybmeta Jan 9 '18 at 9:42
  • @cybmeta Thanks for the reply. See updated answer. Maybe I don't even need the shortcode_atts(); I am totally new to this. – Frank Groot Jan 9 '18 at 9:44
  • I've seen the update question already, no much more information so far. – cybmeta Jan 9 '18 at 9:45
  • I don't know how to explain the problem more deeply than I already did... The 2 in the shortcode gets passed in the function of that shortcode the 2 needs to change according to the shortcode, so when i use [product id="3"] the 2 needs to be a "3". And the request will go according to the param in the sortcode. – Frank Groot Jan 9 '18 at 9:49
  • Ok, I think I understand now. See the answer. – cybmeta Jan 9 '18 at 9:51
1

If you have this shortcode:

[product id="2"]

Which is redered by this:

add_shortcode( 'product', 'getSingleProduct' );
function getSingleProduct( $atts ) {
    shortcode_atts( [
      'id' => '0',
    ], $atts  );

    // Do someting with the "2".
    do_request( 'GET', get_api_url() . 'api/product/' . "2" ); // This "2" comes from the shortcode
}

You can get the shortcode params like this:

add_shortcode( 'product', 'getSingleProduct' );
function getSingleProduct( $atts ) {
    // $atts is an array with the shortcode params
    // shortcode_atts() function fills the array with the
    // default values if they are missing
    $atts = shortcode_atts( [
      'id' => '0',
    ], $atts  );

    $id = $atts['id'];

    do_request( 'GET', get_api_url() . 'api/product/' . $id );

}
  • I feel so stupid, if i knew $atts was an array with the param as key this wasn't an issue. Thanks for putting me in the right direction. – Frank Groot Jan 9 '18 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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