Guest User

Untitled

a guest
Aug 14th, 2016
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.59 KB | None | 0 0
  1. <? php
  2. add_shortcode('example', function( $atts ) {
  3.     //extracting the shortcode attributes
  4.     extract( shortcode_atts( array(
  5.         'value1' => null,
  6.         'value2' => null,
  7.         'value3' => null
  8.     ), $atts ) );
  9.  
  10.     //Now here I wll do my code for the shortcode
  11.     // But the shortcode needs some js and css to work
  12.     // so, I'm trying like this
  13.  
  14. });
  15.  
  16. add_action ('wp', 'add_shortcode_script');
  17.  
  18. function add_shortcode_script () {
  19.   global $post;
  20. if ( empty($posts) )
  21.         return $posts;
  22.  
  23.     $flag = false;
  24.  
  25. // setting up regex
  26. $regex = '/(\w+)\s*=\s*"(.*?)"/';
  27.  
  28. // running a check inside posts
  29.     foreach ($posts as $post) {
  30.  
  31. // if shortcode found
  32.         if ( stripos($post->post_content, '[EXAMPLE]') ) {
  33.             // set the flag
  34.             $flag = true;
  35. // then run a preg match scan for the variables inside shortcode
  36. preg_match_all($regex, $post->post_content, $matches);
  37. $output = array();
  38. // running the variable scan inside shortcode
  39. for ($i = 0; $i < count($matches[1]); $i++) {
  40.     $output[$matches[1][$i]] = $matches[2][$i];
  41. }
  42.             break;
  43.             }
  44.        }
  45.  
  46.     if ($flag){
  47.  
  48.  //using shortcode variables
  49. $custom_script = 'var a = '. $output[1][value3] .';
  50.  
  51. $custom_style = '.class {
  52.                background-color: '. $output[1][value2] .';
  53.            }';
  54.  
  55. wp_enqueue_script ('my_script','http:/.../main.js'); // blank js file
  56. wp_enqueue_style ('my_style','http:/.../main.css'); // blank css file
  57. wp_add_inline_script ('my_script', $custom_script);
  58. wp_add_inline_style ('my_style', $custom_stle);
  59.   }
  60.   return $posts;
  61. }
Add Comment
Please, Sign In to add comment