Skip to content

Instantly share code, notes, and snippets.

@junaidkbr
Last active December 17, 2017 07:27
Show Gist options
  • Save junaidkbr/c1d264600927f29fc6b39930bd9f53d2 to your computer and use it in GitHub Desktop.
Save junaidkbr/c1d264600927f29fc6b39930bd9f53d2 to your computer and use it in GitHub Desktop.
Migrate abandoned/expired shortcode values to ACF field
<?php
/**
* Plugin Name: Traverse
* Description: A small plugin to look for specific abandoned shortcode in posts, get it's link (a shortcode attribute) and save that value in an ACF field.
* Author Name: Junaid Ahmed
*/
add_action('init', function(){
// post types to target
$post_types = array( 'post' );
$posts = new WP_Query(array(
'post_type' => $post_types,
'posts_per_page' => -1
));
while ( $posts->have_posts() ) {
$posts->the_post();
$content = get_the_content();
// the following regex will match/get anything between the two strings i.e.
// link=" and "
// This regex is based on the shortcode below
// [shortcode link="https://example.com/download/something.zip"]
// so, this needs to change based on your expired shortcode structure
$regex = '/link="(.*)"/';
preg_match($regex, $content, $link);
// $link[1] contains have our matched link i.e.
// https://example.com/download/something.zip
// check if there was a match
if ( count($link) ) {
// save the matched link to your ACF field
// replace YOUR_ACF_FIELD_NAME with the ACF field you need to save the matched link in
update_field('YOUR_ACF_FIELD_NAME', $link[1], get_the_ID());
// while we are at it, why don't we remove the shortcode from the post
// replace YOUR_SHORTCODE_NAME with your shortcode name and you're good to go
wp_update_post(array(
'ID' => get_the_ID(),
'post_content' => preg_replace('/\[YOUR_SHORTCODE_NAME(.*)\]/', '', get_the_content())
));
}
}
// assuming that our work is pretty much done
// let's deactivate this plugin
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
deactivate_plugins( plugin_basename( __FILE__ ) );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment