Snippets

MVF (Not a Very Elegant Way Of) Getting all Used Shortcodes and the Posts They Are Included In

Created by Fernando Paredes Murillo
<?php
/*
Plugin Name: List shortcodes
 */
 
/*
This is a quick hack, not intended to be used in any real application or anything that looks like it.
Simply request your WP site URL with ?shortcodes=true at the end.
The JSONView Chrome Extension does the rest of the magic to visualize it properly.
*/

function get_shortcodes_in_content( $post_content ) : array {
    if (
        preg_match_all( '/\[\e?([a-zA-Z_-]*)\e?.*?\]/ums', $post_content, $matches )
        && array_key_exists( 1, $matches )
    ) {
        $shortcodes = array_unique( $matches[1] );
        $shortcodes = array_filter( $shortcodes );
        return $shortcodes;
    }

    return [];
}

function list_shortcodes() {
    global $post;
    if ( isset( $_GET['list-shortcodes'] ) && 'true' === $_GET['list-shortcodes']) {
        $query = new WP_Query( [
            'posts_per_page'   => -1,
            'post_type'        => ['post', 'page'],
        ] );

        $list = [];

        while ( $query->have_posts() ) {
            $query->the_post();

            foreach (  get_shortcodes_in_content( $post->post_content ) as $post_shortcode ) {
                if( ! isset( $list[$post_shortcode] ) ){
                    $list[$post_shortcode] = [];
                }

                $list[$post_shortcode][] = $post->ID;
            }
        }

        ksort( $list, SORT_STRING | SORT_FLAG_CASE );
        echo json_encode($list);

        wp_reset_query();

        die();
    }
}
add_action( 'init', 'list_shortcodes' );

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.