I have a WordPress plugin that is creating pages on activation, but I only want it to create the pages if they don't already exist (don't want duplicates if the plugin has been re-activated).
<?
function create_pages() {
if ( ! current_user_can( 'activate_plugins' ) ) return;
$pages = array(
// Donations
array(
'post_title' => 'Donations',
'post_content' => 'Give us all your money!',
),
// Cart
array(
'post_title' => 'Cart',
'post_content' => 'Buy!',
),
);
foreach($pages as $page) {
if(get_page_by_title($page['post_title']) === null):
$new_post = array(
'post_title' => $page['post_title'],
'post_content' => $page['post_content'],
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
endif;
}
}
register_activation_hook(__FILE__, 'create_pages');
When I run this, no pages are created and it seems to be caused by the if(get_page_by_title($page['post_title']) === null):
line. If I leave that conditional out, it creates the pages needed - but also recreates them on reactivation.
Is there anything glaring I'm missing? Any help is greatly appreciated.
Thanks!
My Answer:
You can achieve this by checking if the post title already exists before creating a new page. Here's an example code snippet that you can use in your plugin file:
php
register_activation_hook( __FILE__, 'create_page_on_activation' );
function create_page_on_activation() {
$page_title = 'Your Page Title';
$page_content = 'Your Page Content';
$page_check = get_page_by_title( $page_title );
if( empty( $page_check ) ) {
$page = array(
'post_title' => $page_title,
'post_content' => $page_content,
'post_status' => 'publish',
'post_type' => 'page'
);
wp_insert_post( $page );
}
}
In this code snippet, we first define the page title and content that you want to create. We then use the `get_page_by_title` function to check if a page with the specified title already exists. If the page does not exist (`$page_check` is empty), we create a new page using the `wp_insert_post` function.
Make sure to replace `'Your Page Title'` and `'Your Page Content'` with your actual page title and content. You can add this code to your plugin file to create a new page only if it does not already exist.
Rate this post
4 of 5 based on 2938 votesComments