One approach you could take is to move the registration of the custom post type and taxonomy to the register_activation_hook
function, so that they are registered before the posts are created.
Here’s an example:
function my_plugin_activate() {
// Register the custom post type and taxonomy
register_post_type( 'question', $args );
register_taxonomy( 'role', array( 'question' ), $args );
// Create the posts
$posts = array(
array(
'title' => 'Question 1',
'role' => 'Role 1',
'competence_id' => '1'
),
array(
'title' => 'Question 2',
'role' => 'Role 2',
'competence_id' => '2'
),
// Add more posts as needed
);
foreach ( $posts as $post ) {
$post_id = wp_insert_post( array(
'post_title' => $post['title'],
'post_status' => 'publish',
'post_type' => 'question',
'tax_input' => array(
'role' => array_map( 'trim', explode( ',', $post['role'] ) )
),
'meta_input' => array(
'_competence_id' => $post['competence_id']
)
) );
}
}
register_activation_hook( __FILE__, 'my_plugin_activate' );
In this example, the custom post type and taxonomy are registered within the my_plugin_activate
function using the register_post_type
and register_taxonomy
functions. The posts are then created using the wp_insert_post
function, which includes the tax_input
parameter to assign the appropriate taxonomy terms.
By registering the custom post type and taxonomy within the activation hook, you ensure that they are available when the posts are created, and the taxonomy terms are assigned correctly.
Thanks Linards,
so I call register_post_type and register_taxonomy twice, both on plugin activation and using the ‘init’ hook, right?
Yes, that’s correct. You’ll register the custom post type and taxonomy within the my_plugin_activate
function for the activation hook, and also register them using the init
hook for normal usage. This ensures that the custom post type and taxonomy are available when the posts are created during activation and during regular use.
Here’s an example:
function my_plugin_register() {
// Register the custom post type and taxonomy
register_post_type( 'question', $args );
register_taxonomy( 'role', array( 'question' ), $args );
}
function my_plugin_activate() {
// Call the registration function
my_plugin_register();
// Create the posts
// ... (the same code as in the previous example)
}
// Register the custom post type and taxonomy during normal usage
add_action( 'init', 'my_plugin_register' );
// Register the custom post type and taxonomy and create posts on activation
register_activation_hook( __FILE__, 'my_plugin_activate' );
By using this structure, you avoid duplicating the registration code and ensure that the custom post type and taxonomy are registered properly during both activation and regular use.