Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active November 13, 2017 21:09
Show Gist options
  • Select an option

  • Save igorbenic/b6e712d0c5e414e95dfa6fec4f8208bc to your computer and use it in GitHub Desktop.

Select an option

Save igorbenic/b6e712d0c5e414e95dfa6fec4f8208bc to your computer and use it in GitHub Desktop.
Find Unused Shortcodes in WordPress with Code | https://www.ibenic.com/unused-shortcodes-wordpress-code
<?php
add_action( 'admin_init', 'ibenic_get_all_posts_shortcodes' );
function ibenic_get_all_posts_shortcodes() {
if( isset( $_REQUEST['get_shortcodes'] ) ) {
// Our code will go here
die();
}
}
<?php
// This goes outside the query loop
echo 'Possible Unused Shortcodes<br/>';
if( $posts ) {
echo '<ul>';
foreach ($posts as $unused) {
echo '<li>';
// Admin URL so we can edit it immediately
echo '<a href="' . admin_url( 'post.php?post=' . $unused['id'] . '&action=edit' ) . '" >';
echo $unused['link'] . '</a>';
// Showing the possible unused shortcode
echo ' - ' . $unused['shortcode'];
echo '</li>';
}
echo '</ul>';
} else {
echo 'No unused shortcodes. Good Work!';
}
<?php
$args = array(
//Type & Status Parameters
'post_type' => array( 'post', 'page' ),
'post_status' => 'any',
//Pagination Parameters
'posts_per_page' => -1,
);
// In case we have a huge Database
set_time_limit(0);
$query = new WP_Query( $args );
$posts = array();
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// Getting the content and checking for unused shortcodes
// Code inside query loop will go here...
}
wp_reset_postdata();
}
// Code outside query goes here
<?php
// This goes inside the query loop
ob_start();
the_content();
// Getting the parsed content
// where all registered shortcodes have been replaced
$output = ob_get_clean();
// Checking for a shortcode pattern
preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $output, $matches );
// If any match, add it to array
if( $matches[0] ) {
$posts[] = array(
'id' => get_the_id(),
'link' => get_permalink(),
'shortcode' => $matches[1][0] );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment