Gravity forms - get shortcode attribute from post content

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?

Topic plugin-gravity-forms regex shortcode Wordpress

Category Web


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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.