Create page when plugin is activated

I’ve made so that everytime my plugin is activated it’s supposed to create a page. Although i want it to only create the page if it doesn’t exist from before. But what it’s doing is that it’s creating another page with kns-products-1 instead of not doing it at all.

My code so far:

function kns_install() {
    global $wp_version;

    if( version_compare( $wp_version, '3.5', '<' ) ) {
        wp_die( 'Detta tilläget kräver att du har WordPress version 3.5 eller högre.' );
    } else {
        if(!is_page('kns-products')) {
            $product_page = array(
            'post_type' => 'page',
            'post_name' => 'kns-products',
            'post_title' => 'Produkter',
            'post_status' => 'publish',
            );

            wp_insert_post($product_page);
        }
    }   
}

I thought that the !is_page condition would solve this but there seems to be a built in code to just add numbers after the slug name.

Is there any way to solve this or does anyone know of any better approach?

1 Answer
1

Since you want to check for a certain page, you could use one of the following functions, for instance:

  • get_post: Takes a post ID and returns the database record for that post, which can also be a page.
  • get_page_by_title: Retrieves a post given its title. If more that one post uses the same title, the post with the smallest ID will be returned.

Or you could write your own little function to get the page by its slug:

function get_page_by_slug($slug) {
    if ($pages = get_pages())
        foreach ($pages as $page)
            if ($slug === $page->post_name) return $page;
    return false;
} // function get_page_by_slug

You would use it like so then:

if (! get_page_by_slug('kns-products')) {
    ...
}

Leave a Comment