Last active
December 21, 2016 16:57
-
-
Save onigetoc/e968334e5e6feae553f4106d02f493ea to your computer and use it in GitHub Desktop.
Wordpress Filter text widget and shortcode | Allow Shortcode in text widget | Search replace in Text Widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// ENQUEUE IF SHORTCODE IN TEXT WIDGET | |
function check_shortcode($text) { | |
$pattern = get_shortcode_regex(); | |
if ( preg_match_all( '/'. $pattern .'/s', $text, $matches ) | |
&& array_key_exists( 2, $matches ) | |
&& in_array( 'myshortcode', $matches[2] ) ) | |
{ | |
// myshortcode is being used | |
// enqueue my css and js | |
/****** Enqueue styles & scripts ******/ | |
wp_enqueue_style('css-mycss'); | |
wp_enqueue_script('js-myjs'); | |
// OPTIONAL ALLOW SHORTCODE TO WORK IN TEXT WIDGET | |
add_filter( 'widget_text', 'shortcode_unautop'); | |
add_filter( 'widget_text', 'do_shortcode'); | |
} | |
return $text; | |
} | |
add_filter('widget_text', 'check_shortcode'); | |
// SEARCH & REPLACE FILTER IN TEXT WIDGET | |
function exam_plug_text_replace($text) { | |
$search = array('welcome admin','today_data'); | |
$replace = array('welcome adam','9/15/2016'); | |
$text = str_replace($search, $replace, $text); | |
return $text; | |
} | |
add_filter('widget_text', 'exam_plug_text_replace'); | |
/* REMOVE P & BR TAGS INSIDE SHORTCODE */ | |
function shortcodes_filter($content) { | |
$block = join("|",array("shortcode-name1", "shortcode-name2")); | |
$rep = preg_replace("/(<p>)?\[($block)(\s[^\]]+)?\](<\/p>|<br \/>)?/","[$2$3]",$content); | |
$rep = preg_replace("/(<p>)?\[\/($block)](<\/p>|<br \/>)?/","[/$2]",$rep); | |
return $rep; | |
} | |
add_filter("the_content", "shortcodes_filter"); | |
// WRAP SHORTCODE IN SHORTCODE LIKE WP IMAGE CAPTION. | |
function wrap_shortcodes( $atts, $content = null ) { | |
/* REGEX IF NEED TO MATCH CERTAIN SHORTCODE */ | |
//$reg = get_shortcode_regex(); | |
//preg_match_all('/'.$reg.'/s',$content,$matches); | |
//$nbrshortcode = count($matches[0]); | |
//return '<span class="myclassname">' . $content . '</span>'; | |
return $nbrshortcode.'<div class="myclassname">' . do_shortcode($content) . '</div>'; | |
} | |
add_shortcode( 'shortcode-name', 'wrap_shortcodes' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment