Skip to content

Instantly share code, notes, and snippets.

@jesselau76
Created September 25, 2018 04:15
Show Gist options
  • Save jesselau76/edbfc61683eedcce946d516a13bff34c to your computer and use it in GitHub Desktop.
Save jesselau76/edbfc61683eedcce946d516a13bff34c to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Find and Replace TEXT
* Plugin URI: https://jesselau.com
* Version: 2.0
* Author: jesse Lau
* Author URI: https://jesselau.com
* Description: Add find and replace function in WordPress editor in both visual and text mode.
* License: GPL2
*/
class jesse_find_replace_button {
/**
* Constructor. Called when the plugin is initialised.
*/
function __construct() {
if ( is_admin() ) {
function add_media_button() {
printf( '<a href="%s" class="button jesse_find_replace_button" id="jesse_find_replace_button">' . '<span class="wp-media-buttons-icon dashicons dashicons-search"></span> %s' . '</a>', '#', __( 'Find & Replace', 'textdomain' ) );
}
add_action( 'media_buttons', 'add_media_button',100 );
add_action( 'admin_print_footer_scripts', array( &$this, 'admin_footer_scripts' ) );
}
}
function admin_footer_scripts() {
?>
<script type="text/javascript">
jQuery(function($) {
$(document).ready(function(){
$("#jesse_find_replace_button").click(function(){
//WP Editor always use "content" as ID
//
var defaultid = "content";
var text ="";
if($('#wp-content-wrap').hasClass('html-active')){ // We are in text mode
text = $('#content').val(); // get the textarea's content
} else { // We are in tinyMCE mode
var activeEditor = tinyMCE.get(defaultid);
if(activeEditor!==null){ // Make sure we're not calling getContent on null
text = activeEditor.getContent({format : 'raw'});
}
}
if(text=="")
{
alert("You TEXT AREA ID is not default value or you don't have any content in the Editor. Please read help file.");
return;
}
var search = prompt('Find What:');
if( !search)
return;
var pattern = new RegExp(search,"gi");
var findCount = (text.match(pattern) || []).length;
if(findCount == 0){
alert("Nothing found!");
return;
}
var replace = prompt('Replace With:');
if( !replace)
replace="";
if(confirm("find '"+search+"', "+findCount + " matches found, replace with '"+replace+"' now?")){
var retext = text.replace(pattern, replace);
if($('#wp-content-wrap').hasClass('html-active')){ // We are in text mode
$('#content').val(retext); // Update the textarea's content
} else { // We are in tinyMCE mode
var activeEditor = tinyMCE.get(defaultid);
if(activeEditor!==null){ // Make sure we're not calling setContent on null
text = activeEditor.setContent(retext); // Update tinyMCE's content
}
}
}
});
});
});
</script>
<?php
}
}
$jesse_find_replace_button = new jesse_find_replace_button;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment