wordpressvariablesshortcode

I am looking for how to pull the Post ID from a currently active page in Wordpress using Shortcode to apply in a dynamic filter


I am using Shortcode in Wordpress also using Ninja Tables. The code is pulling from a Google Spreadsheet managed by a non-developer admin person. Generally easy. I am looking to embed this in a template rather installing the shortcode manually on all posts.

Following is the shortcode snippit I am using:

[ninja_tables id="446" search=0 filter="1100" filter_column="Filter4" columns="name,address,city,website,facebook"]

I am looking for a way that the shortcode can use a variable in place of the filter value of "1100" so that it automatically fills that with the post ID of the current post. This eliminates the need to hand key the short code on the post. I would then manually add the post ID into the spreadsheet which is far easier to maintain.

I have found references to PHP programming but am not a PHP developer and not trying to get so deep into development solutions. Hoping for a simpler solution with possible variables that can read page details into the shortcode.


Solution

  • Add this to your functions.php file:

    function ninja_table_by_post_id() {
        $post_id = get_the_ID();
    
        $shortcode = '[ninja_tables id="446" search=0 filter="' . $post_id . '" filter_column="Filter4" columns="name,address,city,website,facebook"]';
    
        return do_shortcode($shortcode);
    }
    add_shortcode('current_post_table', 'ninja_table_by_post_id');
    

    This code creates a new shortcode called [current_post_table] that when inserted into any post/page it'll render a table filtered out by the current post ID.

    Usage:

    <?php echo do_shortcode('[current_post_table]'); ?>