Jak stworzyć własne shortcody w wordpress?
function register_shortcodes(){
add_shortcode( 'w_code', 'display_code' );
function display_code(){
return "Some value";
}
}
add_action( 'init', 'register_shortcodes' );
To display shortcode use:
[w_code]
Shortcode z parametrem
function wporg_shortcode( $atts = [] ) {
$wporg_atts = shortcode_atts(
array(
'q' => 0,
), $atts
);
$o = "";
$o .= esc_html__( $wporg_atts['q'], 'wporg' );
return $o;
}
function wporg_shortcodes_init() {
add_shortcode( 'wporg', 'wporg_shortcode' );
}
add_action( 'init', 'wporg_shortcodes_init' );
Przykład pluginu, który wyświetli posty z danej kategorii
function register_shortcodes(){
add_shortcode( 'w_ebooks', 'display_code' );
function display_code(){
$ret = "";
$ret .= '<div class="container xl">';
$ret .= '<div class="ebooks_section_w">';
$args = array(
'post_type' => 'post',
'category_name' => 'ebook',
'post_status' => 'publish',
'order'=>'ASC'
);
$the_query = new WP_Query($args);
if($the_query -> have_posts()){
while($the_query -> have_posts()){
$the_query -> the_post();
$ret .= '<div class="ebook_item_w">';
$ret .= '<a href="'.get_the_permalink().'">';
if ( has_post_thumbnail() ) {
$ret .= get_the_post_thumbnail();
}
$ret .= '</a>';
$ret .= '<h2 class="ebook_title"><a href="'.get_the_permalink().'">'.get_the_title().'</a></h2>';
$ret .= '<p>'.substr(get_the_excerpt(), 0, 200).'...</p>';
$ret .= '</div>'; // end ebook_item_w
}
}
wp_reset_postdata();
$ret .= '</div>'; //end ebooks_section_w
$ret .= '</div>';//end container
return $ret;
}
}
add_action( 'init', 'register_shortcodes' );