shortcode高级参数写法举例

Published
April 21, 2022
浏览次数 :  0

if (!defined('ABSPATH')) {
  // code...
  exit;
}


class Themename_Add_Shoetcode {

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

    add_filter('shortcode_atts__themename_button',array($this,'func'),10,4);


  }

public function _themename_add_shortcodes() {
  add_shortcode( '_themename_button', array($this,'_themename_button' ));
  add_shortcode( '_themename_icon', array($this,'_themename_icon_genetor' ));
  add_shortcode( '_themename_slider', array($this,'_themename_slider' ));
  add_shortcode( '_themename_slide', array($this,'_themename_slide' ));

}

/**
 * $atts = [],$content = null,$tag = ''
 * $tags is the shorcode name define in add_shortcode  can pass in the shortcode_atts function
 * 可以通过$tag 来filter shortcode, no $tags parameter can not add the shortcode_atts__themename_button filter
 */
public function _themename_slider($atts = [],$content = null,$tags = '') {
  ob_start();
  extract(shortcode_atts(array(
    'autoplay'  => false,
    'arrows'  => false

  ),$atts,$tags));

  $output = '<div class="_themename_slider" data-slick=\'{"autoplay":'. ($autoplay ? 'true' : 'false') .',"arrows":' .($arrows ? 'true' : 'false') . '}\'>';

  

  if (!is_null($content)) {
    $output .=  do_shortcode($content);
    // code...
  }

  $output .= '</div>';



  return $output;

}

public function _themename_slide($atts = [],$content = null,$tags = '') {
  ob_start();
  extract(shortcode_atts(array(
    'image'  => null,
    'caption'  => 'dhsjhdkkkjk'

  ),$atts,$tags));

  $output = '<div class="_themename_slide">';
  if ($image) {
    $output .= wp_get_attachment_image( $image,'large' );
    // code...
  } if($caption) {
    $output .= '<div class="_themename_slide_caption"> ' .esc_html( $caption ). '</div>';
  }

  $output .= '</div>';

  return $output;

}

public function func($out,$pairs,$atts,$shortcode) {
  return [
    'color'  => 'yellow',];
}


public function _themename_button($atts = [],$content = null,$tag = '') { //shorcode callback 传递三个参数 $atts,$content,$tag
   
  ob_start();
  extract(shortcode_atts(array(
    'color' => 'blue',
    'text' => 'finebutton'

  ),$atts,$tag));
  
  return '<button style="background:' . $color . '">' . do_shortcode($content) . '</button>';
  ?>

  <?php 
  ob_clean();
  
}

public function _themename_icon_genetor($atts){
  ob_start();
  extract(shortcode_atts( array(
    'icon'  => ''
  ), $atts ));

  return '<i class="'. $icon . '"></i>';

}

}

$themename_shortcode = new Themename_Add_Shoetcode();

Top