igmoweb
5/14/2014 - 9:11 AM

Pinteres Embeds

Pinteres Embeds

<?php

/**
 * Plugin Name: Pinterest embeds
 */

class Pinterest_Embed {

	public $embedded = false;

	public function __construct() {
		add_action( 'init', array( $this, 'init' ) );

		add_action( 'wp_footer', array( $this, 'print_pinterest_init_script' ) );
	}

	public function init() {
		wp_embed_register_handler( 'pinterest-pin', '#http://(www\.)?pinterest\.com/pin/(.*)\/?#i', array( $this, 'pinterest_pin_handler' ) );
		wp_embed_register_handler( 'pinterest-board', '#http://(www\.)?pinterest\.com/(.*)/?#i', array( $this, 'pinterest_board_handler' ) );
	}

	public function pinterest_pin_handler( $matches, $attr, $url, $rawattr ) {
		ob_start();
		?>
			<a data-pin-do="embedPin" href="<?php echo esc_url( $url ); ?>"></a>
		<?php
		$this->embedded = true;
		return ob_get_clean();
	}

	public function print_pinterest_init_script() {
		if ( $this->embedded ) {
			?>
				<script type="text/javascript" async src="//assets.pinterest.com/js/pinit.js"></script>
			<?php
		}

	}

	/**
	 * Handle the board embeds
	 * 
	 * @param type $matches Regex matches
	 * @param type $attr
	 * @param type $url 
	 * @param type $rawattr 
	 * @return type
	 */
	public function pinterest_board_handler( $matches, $attr, $url, $rawattr ) {
		$arg = rtrim( $matches[2], '/' );
		$args = explode( '/', $arg );

		ob_start();
		if ( count( $args ) == 1 ) {
			// A profile embed (user)
			?>
				<a data-pin-do="embedUser" href="<?php echo esc_url( $url ); ?>"></a>
			<?php
			$this->embedded = true;
		}
		elseif ( count( $args == 2 ) ) {
			// A board embed (user/category)
			?>
				<a data-pin-do="embedBoard" href="<?php echo esc_url( $url ); ?>" data-pin-scale-width="80" data-pin-scale-height="320" data-pin-board-width="400"></a>
			<?php
			$this->embedded = true;
		}
		return ob_get_clean();
	}
}

global $pinterest_embed;
$pinterest_embed = new Pinterest_Embed();