Last active
August 29, 2015 14:26
-
-
Save mor7ifer/e50a9864a372a05b4a3b to your computer and use it in GitHub Desktop.
Enqueue Shortcode
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 | |
// Based heavily on http://wordpress.stackexchange.com/a/77946 | |
/** | |
* This class allows child classes to easily enqueue styles and scripts. | |
* | |
* Children of this class should be instantiate as | |
* new Child_Enqueue_Shortcode( 'shortcode-name' ) | |
* and should have methods enqueue() and output_shortcode(). The method enqueue() | |
* should simply have wp_enqueue_style() and wp_enqueue_script() (as well as | |
* wp_register_*()) calls. The output_shortcode() method should contain the HTML | |
* for display of the shortcode. | |
*/ | |
abstract class Enqueue_Shortcode { | |
/** | |
* Properties | |
*/ | |
public $shortcode_name; | |
public $post_meta_key; | |
/** | |
* Methods | |
*/ | |
abstract protected function output_shortcode( $attributes, $content ); | |
abstract protected function enqueue(); | |
public function __construct( $shortcode_name ) { | |
$this->shortcode_name = $shortcode_name; | |
$this->post_meta_key = md5( $shortcode_name ); | |
add_shortcode( $this->shortcode_name, array( $this, 'do_shortcode' ) ); | |
add_action( 'save_post', array( $this, 'save_post' ) ); | |
add_action( 'wp_print_styles', array( $this, 'wp_print_styles' ) ); | |
} | |
public function do_shortcode( $attributes, $content ) { | |
$this->output_shortcode( $attributes, $content ); | |
} | |
public function save_post( $post_id ) { | |
$post = get_post( $post_id ); | |
if ( has_shortcode( $post->post_content, $this->shortcode_name ) ) { | |
$this->found_shortcode( $post_id ); | |
} else { | |
$this->found_no_shortcode( $post_id ); | |
} | |
} | |
public function wp_print_styles( $args ) { | |
global $post; | |
if ( 'yes' == get_post_meta( $post->ID, $this->post_meta_key, true ) ) { | |
$this->enqueue(); | |
} | |
} | |
protected function found_shortcode( $post_id ) { | |
update_post_meta( $post_id, $this->post_meta_key, 'yes' ); | |
} | |
protected function found_no_shortcode( $post_id ) { | |
update_post_meta( $post_id, $this->post_meta_key, 'no' ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment