Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm building a function that creates a group of pages with a common parent ID.

If I run wp_insert_post() on a parent ID twice, does the function create the pages twice while altering the slugs? Or am I safe to put this in my functions.php like so:

add_action('init', 'AddMyPages');
share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

Use some type of conditional tag to check if those posts exist or not. If they do not exist, have them created with wp_insert_post. Do this logic inside the AddMyPages function and not around the add_action function.

Example

You want to add a page with a parent ID only if it does not exist, and want this page to always exist. Since it's in the init hook, it'll always check if that page exists, so it's not really recommended to do it this way. You should actually do this on activation of a plugin (so I've edited my answer for that method).

register_activation_hook( __FILE__, 'AddThisPage' );

function AddThisPage() {
    global $wpdb; // Not sure if you need this, maybe

    $page = array(
        'post_title' => 'My post',
        'post_content' => 'This is my post.',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type' => 'page',
        'post_parent' => 3 // ID of the parent page
    );

    $page_exists = get_page_by_title( $page['post_title'] );

    if( $page_exists == null ) {
        // Page doesn't exist, so lets add it
        $insert = wp_insert_post( $page );
        if( $insert ) {
            // Page was inserted ($insert = new page's ID)
        }
    } else {
        // Page already exists
    }

}

Thanks @kaiser for reminding me, register_activation_hook only runs in plugins, not themes.

As for a theme, well I don't know of an official activation hook, just switch_theme but that is run before the theme is active. I found a workaround here but it may be out of date, could be something useful to look into.

Resources used

wp_insert_post, get_page_by_title, register_activation_hook

share|improve this answer
    
Thanks! Since I want to have multiples of the same title I'm going to check for the post_name not the title. –  AlxVallejo Jan 24 '12 at 21:08
    
@AlxVallejo In that case, you may want to see the function get_page_by_path. –  Jared Jan 24 '12 at 21:10
2  
@Jared the activation hook(s and similar) is not present for Themes :) –  kaiser Jan 24 '12 at 21:27
    
You are right, I hadn't even realized that. Thanks! –  Jared Jan 24 '12 at 21:34
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.