Skip to content

Instantly share code, notes, and snippets.

@kaelri
Created November 11, 2021 22:29
Show Gist options
  • Save kaelri/f8b0a2b141f522d1c0f53035599544e6 to your computer and use it in GitHub Desktop.
Save kaelri/f8b0a2b141f522d1c0f53035599544e6 to your computer and use it in GitHub Desktop.
Create a WordPress post whose content can be included in other posts via a shortcode.
<?php
class sharedBlocks {
public static function setup() {
add_action( 'init', [ __CLASS__, 'register_post_type' ], 0 );
add_shortcode( 'shared', [ __CLASS__, 'do_shortcode' ] );
}
public static function register_post_type() {
register_post_type( 'shared', [
'supports' => [ 'title', 'editor' ],
'show_in_rest' => true,
'taxonomies' => [],
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 20,
'menu_icon' => 'dashicons-slides',
'can_export' => true,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'capability_type' => 'post',
'labels' => [
'name' => 'Shared Block Containers',
'singular_name' => 'Shared Block Container',
'menu_name' => 'Shared',
'parent_item_colon' => 'Parent Shared Block Container:',
'all_items' => 'All Shared Block Containers',
'view_item' => 'View Shared Block Containers',
'add_new_item' => 'Add New Shared Block Container',
'add_new' => 'New Shared Block Container',
'edit_item' => 'Edit Shared Block Container',
'update_item' => 'Update Shared Block Container',
'search_items' => 'Search Shared Block Containers',
'not_found' => 'No Shared Block Containers Found',
'not_found_in_trash' => 'No Shared Block Containers Found in Trash',
],
]);
}
function do_shortcode( $atts, $content = '' ) {
// ATTRIBUTES
extract( shortcode_atts([
'id' => 0
], $atts ));
// Abort if the ID is empty or matches the current post.
if ( empty($id) || (int) $id == get_the_ID() ) return;
$shared_post = get_post( (int) $id );
$content = apply_filters( 'the_content', $shared_post->post_content );
return $content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment