Skip to content

Instantly share code, notes, and snippets.

@luancmaia
Created October 2, 2014 02:14
Show Gist options
  • Save luancmaia/9d5b6d065db6fd260b1d to your computer and use it in GitHub Desktop.
Save luancmaia/9d5b6d065db6fd260b1d to your computer and use it in GitHub Desktop.
Shortcode to restrict a piece of content
<?php
Class Shortcode {
public function __construct(){
add_shortcode( 'restricted:content', array( &$this, 'restricted_content' ) );
}
private function explode_params( $params = null, $flag = ',' ){
if ( is_null( $params ) || empty( $params ) ) {
return null;
}
if ( stripos( $params, $flag ) !== false ) {
$params = explode( $flag, $params );
}
return array_map( 'trim', (array) $params );
}
private function filter_params( $params = null, $flag = '-' ){
$results = array(
array(),
array(),
);
if ( is_null( $params ) || empty( $params ) ) {
return $results;
}
foreach( (array) $params as $param ) {
if ( empty( $param ) || !is_string( $param ) ) {
continue;
}
if ( stripos( $param, $flag ) === false ) {
$results[0][] = $param;
} else {
$results[1][] = str_replace($flag, '', $param );
}
}
return $results;
}
public function restricted_content( $data, $content = null ){
$data = (object) shortcode_atts( array(
'role' => '',
'user' => '',
'tax' => '',
'post_type' => '',
), $data );
if ( !empty( $data->role ) ) {
list( $data->role__in, $data->role__not_in ) = $this->filter_params( $this->explode_params( $data->role ) );
}
if ( !empty( $data->user ) ) {
list( $data->user__in, $data->user__not_in ) = $this->filter_params( $this->explode_params( $data->user ) );
}
if ( !empty( $data->tax ) ) {
list( $data->tax__in, $data->tax__not_in ) = $this->filter_params( $this->explode_params( $data->tax ) );
}
if ( !empty( $data->post_type ) ) {
list( $data->post_type__in, $data->post_type__not_in ) = $this->filter_params( $this->explode_params( $data->post_type ) );
}
return '<pre>' . print_r( $data, true ) . '</pre>';
}
}
$s = new Shortcode();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment