• Hi there, I’ve created a plugin that creates a CPT called Locations. the CPT Locations also has a couple of custom meta fields like api key location id etc. Those meta field boxes are also created with that plugin.

    Now to save me from repetitive work. I want to create a loop, that inserts 25 specific locations, everytime I install/activate the plugin.

    I’ve looked online on how to do it. I’ve found out that I could just create an array for those 25 locations, and loop through it with wp_insert_post($location). But how do I insert those meta box values at the same time?

    I know that you need a post ID to add a meta-value to a specific post, but I don’t have that post->ID yet, because of the foreach. Any ideas?

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter janmoes

    (@janmoes)

    I managed to fix it like this:

    register_activation_hook(__FILE__, 'activate_cpt_locations');
    function activate_cpt_locations(){
    	$locations = [
    		[
    		  'post_title'   => 'Amsterdam',
    			'post_content' => '',
    			'post_status'  => 'publish',
    			'post_type'    => 'location',
    			'meta_input'   => [
    				'_location_id' => 13529,
    				'_sportivity_api_key'   => 123456,
    				'_clubplanner_username' => 'user',
    				'_clubplanner_password' => 'pass',
    			],
    		],
    		[
    		  'post_title'   => 'Delft',
    			'post_content' => '',
    			'post_status'  => 'publish',
    			'post_type'    => 'location',
    			'meta_input'   => [
    				'_location_id' => 13529,
    				'_sportivity_api_key'   => 123456,
    				'_clubplanner_username' => 'user',
    				'_clubplanner_password' => 'pass',
    			],
    		],
    	];
    	
    	foreach($locations as $location){
    		wp_insert_post($location);
    	}
    }
    
    register_deactivation_hook(__FILE__, 'deactivate_cpt_locations');
    function deactivate_cpt_locations(){
    	$locations = get_posts(['post_type'=>'location','numberposts'=>-1]);
    	foreach ($locations as $location) {
    		wp_delete_post( $location->ID, true );
    	}
    }
    
    add_action('init', 'register_location_cpt');
    function register_location_cpt(){
    	$labels = array(
     		'name' => 'Location',
        	'singular_name' => 'Location',
        	'add_new' => 'Add New Location',
        	'add_new_item' => 'Add New Location',
        	'edit_item' => 'Edit Location',
        	'new_item' => 'New Location',
        	'all_items' => 'All Locations',
        	'view_item' => 'View Location',
        	'search_items' => 'Search Locations',
        	'not_found' =>  'No Locations Found',
        	'not_found_in_trash' => 'No Locations found in Trash', 
        	'parent_item_colon' => '',
        	'menu_name' => 'Location',
        );
        //register post type
    	register_post_type( 'Location', array(
    		'labels' => $labels,
    		'has_archive' => true,
     		'public' => true,
    		'supports' => array( 'title', 'thumbnail','page-attributes'),
    		'taxonomies' => array( 'post_tag', 'category' ),	
    		'exclude_from_search' => false,
    		'capability_type' => 'post',
    		'rewrite' => array( 'slug' => 'locations' ),
    		)
    	);
    }

    Is it correct that the locations are inserted in the activation hook? And that the post type is made in the init hook?

    Moderator bcworkz

    (@bcworkz)

    That’s right. Because post data persists in the DB, it only needs to be done once. OTOH, a post type is an abstract construct that does not persist in the DB, so it must be registered for every request through “init” or similar.

    I know it’s a work in progress, but think carefully about deleting data on the deactivation hook. People sometimes have a need to temporarily deactivate plugins and may not want to have the related data deleted. At least give them the option to keep it while deactivating. There is also a plugin removal hook you could use to clean things up instead of during deactivation.

    Thread Starter janmoes

    (@janmoes)

    Yeah I thought so too. If I register the Post Type in the activation hook, it would not exist after activating and refreshing the page. The content is being saved in the db, so that’s okay. But as I understand Init is a hook that runs on every request?

    And which removal hook were you talking about?

    Moderator bcworkz

    (@bcworkz)

    Correct again. It’ll be needed if the post type is referenced anywhere in code. It doesn’t even need to be actively in use, any passive reference at all will throw errors if the post type is not registered. It’s more fuss to try and determine if the registration is needed than to just register it every time regardless. Registration is largely just assigning relevant data to a particular global array.

    An astoundingly large amount of code and data needs to be setup when WP is initialized for any request. Registering a post type is an extremely small part of that. As it’s essentially static data (but not formally static in code), it’s faster to declare it every time than it is to fetch similar data from the DB.

    Plugin Removal (uninstall) Hook. You could instead create an uninstall.php file if you prefer.

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Creating custom post type items with meta fields’ is closed to new replies.