0

I am programatically inserting a new page, then I want to use the ID of that new page to add a template, however wp_insert_post isn't returning me any ID, here's the code I am using

$tittle = 'My new page';
$newPage = array(
        'post_type'     => 'page',
        'post_title'    => $tittle,
        'post_status'   => 'publish'
    );
$post_id = wp_insert_post( $newPage);
print_r($post_id);

in reallity I use the code this way

function criar_pag($titulo, $template = 0){
    $a = get_page_by_title( $titulo, 'post' );
    if ($a == null || $a->post_status == 'trash') {
        $pagina = array(
            'post_type'     => 'page',
            'post_title'    => $titulo,
            'post_status'   => 'publish'
        );
        $post_id = wp_insert_post( $pagina);
        update_post_meta($post_id, '_wp_page_template', $template);
    }
}
criar_pag("my new page", "customtemplate.php");

1 Answer 1

1

I've just tested your code in a function hooked on wp_body_open and it works:

add_action( 'wp_body_open', 'function_test' );
function function_test() {
    $tittle = 'My new page';
    $newPage = array(
        'post_type'     => 'page',
        'post_title'    => $tittle,
        'post_status'   => 'publish'
    );
    $post_id = wp_insert_post( $newPage);
    print_r($post_id);
}

Where do you use this code ?

4
  • Hi, and thanks, I had update the answer with the inteire function, I had notice the $post_id doesnt return, thats why the template isnt be inserted Jan 4 at 9:24
  • your code even without the add_action it works for me also, but my function inside my function it doesnt, let me check this... Jan 4 at 9:27
  • 1
    Where do you use your functions? Maybe you launch it to early. On which hook ? Jan 4 at 9:45
  • 1
    I have to agree with @SébastienSerre here - it's probably because you're running it on the wrong action-hook. I've never seen the "criar_pag" before - you should really use WordPress' core hooks instead.
    – WPTricksDK
    Jan 4 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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