• Resolved Rajarshi Bose

    (@truthsearcher83)


    While checking the code of a plugin which creates a custom post I am seeing the developer checking if the request is for the backend using is_admin() and then including the file to register the custom post type and custom field .

    // Check if admin
    if(is_admin()){
    	// Load Custom Post Type
    	require_once(plugin_dir_path(__FILE__) . '/includes/my-todo-list-cpt.php');
    
    	// Load Custom Fields
    	require_once(plugin_dir_path(__FILE__) . '/includes/my-todo-list-fields.php');
    } 

    All this while I creatingwas create custom posts /fields without using is_admin() without any problem . The custom post/fields do not show in the front end if I do not check using is_admin() . Could you anybody tell me whats the benefit of using is_admin() while creating a custom post ? Is it a normal practise specially in production code to code like above ?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Your question is out of context. The code in those files might be included in a different way on the front end or the REST API. Since we don’t know what is in the file or what that part of the code is really doing, your question can’t be answered.
    You could ask at the plugin’s support forum, though. Or read other plugin’s code to get a more balanced view.

    Post types do have to be registered on each request, or WP doesn’t know about them.

    Thread Starter Rajarshi Bose

    (@truthsearcher83)

    Hi , the code is registering a custom post type and adding a metabox in the backend .I have put the code below . This is a tutorial that I am doing to understand how plugins are developed so there is no plugin support page . I guess the question I want to ask is if I am registering a custom post type using register_post_type(‘todo’, $args); on init hook do I need to check if its the backend using is_admin() before including the file which has the callback for register_post_type() ?

    includes/my-todo-list-cpt.php

    <?php
    	
    	// Create Custom Post Type
    	function mtl_register_todo(){
    		$singular_name = apply_filters('mtl_label_single', 'Todo');
    		$plural_name = apply_filters('mtl_label_plural', 'Todos');
    
    		$labels = array(
    			'name' 				=> $plural_name,
    			'singular_name' 	=> $singular_name,
    			'add_new'           => 'Add New',
    			'add_new_item'      => 'Add New '. $singular_name,
    			'edit'				=> 'Edit',
    			'edit_item'			=> 'Edit '. $singular_name,
    			'new_item'			=> 'New ' .$singular_name,
    			'view'				=> 'View',
    			'view_item'			=> 'View '. $singular_name,
    			'search_items'		=> 'Search '. $plural_name,
    			'not_found'			=> 'No '.$plural_name. ' Found',
    			'not_found_in_trash'=> 'No '.$plural_name. ' Found',
    			'menu_name'			=> $plural_name
    		);
    
    		$args = apply_filters('mtl_todo_args', array(
    			'labels'        	=> $labels,
    			'description'   	=> 'Todos by category',
    			'taxonomies'    	=> array('category'),
    			'public'			=> true,
    			'show_in_menu'		=> true,
    			'menu_position'		=> 5,
    			'menu_icon'			=> 'dashicons-edit',
    			'show_in_nav_menus'	=> true,
    			'query_var'			=> true,
    			'can_export'		=> true,
    			'rewrite'			=> array('slug' => 'todo'),
    			'capability_type'	=> 'post',
    			'supports'			=> array(
    				'title'
    			)
    		));
    
    		// Register Post Type
    		register_post_type('todo', $args);
    	}
    
    	add_action('init', 'mtl_register_todo');

    includes/my-todo-list-fields.php

    <?php
    	function mtl_add_fields_metabox(){
    		add_meta_box(
    			'mtl_todo_fields',
    			__('Todo Fields'),
    			'mtl_todo_fields_callback',
    			'todo',
    			'normal',
    			'default'
    		);
    	}
    
    	add_action('add_meta_boxes', 'mtl_add_fields_metabox');
    
    	// Display Fields Metabox Content
    	function mtl_todo_fields_callback($post){
    		wp_nonce_field(basename(__FILE__), 'wp_todos_nonce');
    		$mtl_todo_stored_meta = get_post_meta($post->ID);
    		?>
    			<div class="wrap todo-form">
    				<div class="form-group">
    					<label for="priority"><?php esc_html_e('Priority', 'mtl_domain'); ?></label>
    					<select name="priority" id="priority">
    						<?php
    							$option_values = array('Low', 'Normal', 'High');
    							foreach($option_values as $key => $value){
    								if($value == $mtl_todo_stored_meta['priority'][0]){
    									?>
    										<option selected><?php echo $value; ?></option>
    									<?php
    								} else {
    									?>
    										<option><?php echo $value; ?></option>
    									<?php
    								}
    							}
    						?>
    					</select>
    				</div>
    
    				<div class="form-group">
    					<label for="details"><?php esc_html_e('Details', 'mtl_domain'); ?></label>
    					<?php
    						$content = get_post_meta($post->ID, 'details', true);
    						$editor = 'details';
    						$settings = array(
    							'textarea_rows' => 5,
    							'media_buttons' => true
    						);
    
    						wp_editor($content, $editor, $settings);
    					?>
    				</div>
    
    				<div class="form-group">
    					<label for="due_date"><?php esc_html_e('Due Date', 'mtl_domain'); ?></label>
    					<input type="date" name="due_date" id="due_date" value="<?php if(!empty($mtl_todo_stored_meta['due_date'])) echo esc_attr($mtl_todo_stored_meta['due_date'][0]); ?>"> 
    				</div>
    			</div>
    		<?php
    	}
    
    	function mtl_todos_save($post_id){
    		$is_autosave = wp_is_post_autosave($post_id);
    		$is_revision = wp_is_post_revision($post_id);
    		$is_valid_nonce = (isset($_POST['wp_todos_nonce']) && wp_verify_nonce($_POST['wp_todos_nonce'], basename(__FILE__)))? 'true' : 'false';
    	
    		if($is_autosave || $is_revision || !$is_valid_nonce){
    			return;
    		}
    
    		if(isset($_POST['priority'])){
    			update_post_meta($post_id, 'priority', sanitize_text_field($_POST['priority']));
    		}
    
    		if(isset($_POST['details'])){
    			update_post_meta($post_id, 'details', sanitize_text_field($_POST['details']));
    		}
    
    		if(isset($_POST['due_date'])){
    			update_post_meta($post_id, 'due_date', sanitize_text_field($_POST['due_date']));
    		}
    	}
    
    	add_action('save_post', 'mtl_todos_save');

    Post types do have to be registered on each request, or WP doesn’t know about them.

    You don’t have to put that code in separate files, but you can if you want.
    The registration has to happen whether it’s admin or front end.
    The metabox only needs to happen when in the editor.
    The save_post action could be triggered by a plugin that allows front-end editing.
    Each piece needs to be hooked to the correct action, and it’s easier if it’s all in one file. If you want to split it out, you can simply require the files without any checks, but if there are some pieces that are really only used in admin, you can improve performance by putting the require in an if statement.

    Thread Starter Rajarshi Bose

    (@truthsearcher83)

    Thank you .

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Checking for is_admin() while creating custom post’ is closed to new replies.