Insert content block by name/slug using shortcode
-
Hello, this is not a question per se, just a note for anyone else who would like to insert a content block by name/slug using shortcode.
I know there’s a handy “add content block” button above the editor, but using several content blocks within a page and only the IDs showing in the shortcode, it gets difficult to know which block is what. Inside post-widget.php, I changed the function custom_post_widget_shortcode this way:
function custom_post_widget_shortcode( $atts ) { extract( shortcode_atts( array( 'id' => '', 'name' => '', 'class' => 'content_block' ), $atts ) ); $content = ""; if ($id != "") { $args = array( 'post__in' => array( $id ), 'post_type' => 'content_block', ); $content_post = get_posts( $args ); foreach( $content_post as $post ) : $content .= '<div class="'. esc_attr($class) .'">'; $content .= apply_filters( 'the_content', $post->post_content); $content .= '</div>'; endforeach; } else { if ($name != "") { $args = array( 'name' => array( $name ), 'post_type' => 'content_block', 'post_status' => 'publish', 'showposts' => 1, ); $content_post = get_posts( $args ); foreach( $content_post as $post ) : $content .= '<div class="'. esc_attr($class) .'">'; $content .= apply_filters( 'the_content', $post->post_content); $content .= '</div>'; endforeach; } } return $content; }
Sorry for the inelegant code, I can’t figure out a nice way to avoid repetition. Anyway, now it’s possible to use a shortcode like [content_block name=”contact-info”] which helps to show what the block represents, instead of an anonymous ID number.
I just want to add that this plugin has been very useful to me. There are other plugins for doing all kinds of things with custom post types, custom fields, taxonomies, etc., but this plugin gets the job done fast, and helped me to learn how custom post types work.
- The topic ‘Insert content block by name/slug using shortcode’ is closed to new replies.