-
Notifications
You must be signed in to change notification settings - Fork 7
Creating a Shortcode
PB Sandwich Shortcodes using Shortcake
PB Sandwich uses Shortcake in order to add UI interfaces for shortcodes.
Creating shortcodes to extend the functionality of Sandwich is composed of two parts:
- Create a shortcode the normal way using
add_shortcode
, then - Create a Shortcake UI for your shortcode.
You can use this sample file for reference:
lib/shortcode/hello-dolly.php
Nothing too fancy here, just create your shortcode like you would typically. In this sample, we will create a Hello Sandwich shortcode that accepts a string argument, then just prints it out.
Example
add_action( 'init', 'my_shortcode' );
function my_shortcode() {
add_shortcode( 'hello_sandwich', 'hello_sandwich_shortcode' );
}
function hello_sandwich_shortcode( $attr, $content ) {
$attr = wp_parse_args( $attr, array(
'name' => 'Sandwich',
) );
ob_start();
printf( __( 'Hello %s' ), esc_html( $attr['name'] ) );
return ob_get_clean();
}
One major difference in Sandwich shortcodes is that we need to perform an ob_start()
and return ob_get_clean()
when returning the output of the shortcode. These function calls are necessary for Sandwich.
The above code will make available the shortcode [hello_sandwich]
. At this point, the shortcode should work fine, but it won't be drag and droppable inside PB Sandwich, and it won't have an interface yet.
We won't dwell too much into the details for creating Shortcake UIs (the UI arguments, etc), since they have covered this topic pretty well in their project page: Shortcake GitHub repo We'll just dive into an example and explain a little bit what the example does.
Example
add_action( 'init', 'hello_sandwich_shortcode_ui' );
function hello_sandwich_shortcode_ui() {
// Check if Shortcake exists
if ( ! function_exists( 'shortcode_ui_register_for_shortcode' ) ) {
return;
}
// Only create the UI when in the admin
if ( ! is_admin() ) {
return;
}
// Create our UI
shortcode_ui_register_for_shortcode(
'hello_sandwich',
array(
'label' => 'Hello Sandwich',
'listItemImage' => 'dashicons-wordpress',
'attrs' => array(
array(
'label' => __( 'Hello' ),
'attr' => 'name',
'type' => 'text',
'value' => 'Sandwich',
),
),
)
);
}
The function above enables the shortcode hello_sandwich
to be included in the list of shortcodes available in Sandwich. It also creates a user interface where users would be able to enter arguments for it. In our case, we are adding a text field that corresponds to the name
attribute of the shortcode with the default value being "Sandwich"
Also, your shortcode becomes rendered within the visual editor in WordPress, and it would now be drag and droppable within the editor.