Search Posts

CPT plugin

<?php
/*
 * Plugin Name: CPT Guido
 * Description: Example plugin that adds Guido post type.
 * Version: 0.1
 * Author: Guido
 * Author URI: https://www.guido.site
 * License: GNU General Public License v3 or later
 * License URI: https://www.gnu.org/licenses/gpl-3.0.html
 */

// disable direct access
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// create guido post type
function add_post_type() {
	$labels = array(
		'name' => esc_attr__( 'Guido', 'text-domain' )
	);
	$args = array(
		'labels' => $labels,
		'public' => true,
		'can_export' => false,
		'show_in_nav_menus' => false,
		'has_archive' => false,
		'show_ui' => true,
		'show_in_rest' => true,
		'capability_type' => 'post',
		'supports' => array('title', 'editor'),
	);
	register_post_type( 'guido', $args );
}
add_action( 'init', 'add_post_type' );


// create metabox
function add_metabox() {
	add_meta_box(
		'cpt-example-metabox',
		esc_attr__( 'Guido Meta', 'text-domain' ),
		'metabox_callback',
		'guido',
		'normal',
		'high'
	);
}
add_action( 'add_meta_boxes', 'add_metabox' );

function metabox_callback( $post ) {
	// generate a nonce field
	wp_nonce_field( 'cpt_meta_box', 'cpt_nonce' );
	
	// get previously saved meta values (if any)
	$field_1 = get_post_meta( $post->ID, 'cpt-field-one', true );
	$field_2 = get_post_meta( $post->ID, 'cpt-field-two', true );

	// metabox fields
	?>
	
	<p><label for="cpt-field-one"><?php esc_attr_e( 'Field 1', 'text-domain' ); ?></label>
	<input class="widefat" id="cpt-field-one" type="text" name="cpt-field-one" value="<?php echo esc_attr( $field_1 ); ?>" /></p>
	<p><label for="cpt-field-two"><?php esc_attr_e( 'Field 2', 'text-domain' ); ?></label>
	<input class="widefat" id="cpt-field-two" type="text" name="cpt-field-two" value="<?php echo esc_attr( $field_2 ); ?>" /></p>
	<?php
}


// save
function save_fields( $post_id ) {
	// check if nonce is set
	if ( ! isset( $_POST['cpt_nonce'] ) ) {
		return;
	}
	// verify that nonce is valid
	if ( ! wp_verify_nonce( $_POST['cpt_nonce'], 'cpt_meta_box' ) ) {
		return;
	}
	// if this is an autosave, our form has not been submitted, so do nothing
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
	// check user permission
	if ( ( get_post_type() != 'guido' ) || ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}
	if ( isset( $_POST['cpt-field-one'] ) ) {
		update_post_meta( $post_id, 'cpt-field-one', sanitize_text_field( $_POST['cpt-field-one'] ) );
	}
	if ( isset( $_POST['cpt-field-two'] ) ) {
		update_post_meta( $post_id, 'cpt-field-two', sanitize_text_field( $_POST['cpt-field-two'] ) );
	}
}
add_action( 'save_post', 'save_fields' );