1

I have some posts and some of them contain [gravityform] shortcode with different attribute values.

Say, a post Hello World contains a shortcode [gravityform id="1" title="false" description="false"]

Another post Hello Moon contains shortcode [gravityform description="true" id="23" title="true"]

How can I get the value of id attribute of that shortcode programmatically?

  • As you can see in the interaction below, pulling that info from the content can be tricky. Perhaps if you elaborate on what you plan to do with the id we could solve the problem differently. – Jeremy Ross Sep 2 '16 at 2:51
0

If you only have 1 shortcode in the post content, catch the id with this:

<?php
    $text = get_the_content();
    preg_match_all("\bid="([0-9]+)\b", $text, $matches);
    var_dump($matches[0]);
?>

In your example [gravityform description="true" id="23" title="true"], it would output:

23

However, if you use other shortcodes or simple text, in the same post, with that same structure id=123, you might get unexpected outputs: it will catch only the first one it finds in the post.

Otherwise you could try this (untested):

    $post_content = get_the_content();

    $start = '[gravityform id="';
    $end = '"';
    $post_content = ' ' . $post_content;
    $ini = strpos($post_content, $start);
    if ($ini === 0) return '';
    $ini += strlen($start);
    $len = strpos($post_content, $end, $ini) - $ini;

    $the_id = substr($post_content, $ini, $len);

    echo $the_id; // 23 in your example

However, you would always have to format it with id as first parameter.

  • That would also catch the id of [other_shortcode id=55] which could have unintended results. – Jeremy Ross Sep 1 '16 at 23:01
  • Yes, I'll specify that. – The J Sep 1 '16 at 23:07
  • 1
    I'm really not trying to pick on you @The J, but in the example, @mukto90 flips the order of arguments between "Hello World" and "Hello Moon" so your second option wouldn't work unless id was always the first argument listed. Another problem is your comparison $ini == 0. this will return true if strpos returns false because PHP is so loosely typed, 0 and false are equal. You'll need to clarify $ini === 0 so you don't get a false positive. – Jeremy Ross Sep 2 '16 at 2:49
  • 1
    No worries! I like constructive advice! First point, forgot to mention explicitly, second point good call! – The J Sep 2 '16 at 2:52

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.