Skip to content

Instantly share code, notes, and snippets.

@davidfcarr
Last active January 30, 2022 18:43
Show Gist options
  • Save davidfcarr/0c832496b1c177e97791891f7fd3b562 to your computer and use it in GitHub Desktop.
Save davidfcarr/0c832496b1c177e97791891f7fd3b562 to your computer and use it in GitHub Desktop.
<?php
/*
* Adds variation on a block theme's single template for custom post type
* called on plugin activation or after_theme_switch action
*/
register_activation_hook( __FILE__, 'rsvpmaker_single_block_template' );
add_action('after_switch_theme','rsvpmaker_single_block_template');
function rsvpmaker_single_block_template() {
global $rsvp_template_done;
if(!function_exists('get_block_templates') || $rsvp_template_done)
return;
$rsvp_template_done = true; // don't do twice
$templates = get_block_templates();
foreach($templates as $template) {
if($template->slug == 'single') {
$rsvpmaker_content = $template->content;
$theme = $template->theme;
}
if($template->slug == 'single-rsvpmaker') {
return; // if already exists, don't add
}
}
if(!empty($rsvpmaker_content)) // found existing template, not stopped by existing rsvpmaker template
{
$rsvpmaker_content = preg_replace('/<[^a-z]+wp:post-(date|author)[^>]+>/','',$rsvpmaker_content);
$new['post_name'] = 'single-rsvpmaker';
$new['post_type'] = 'wp_template';
$new['post_status'] = 'publish';
$new['post_excerpt'] = 'Single event from RSVPMaker';
$new['post_title'] = 'RSVPMaker Single';
$new['post_content'] = $rsvpmaker_content;
$post_id = wp_insert_post($new);
wp_add_object_terms($post_id,$theme,'wp_theme');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment