update_post_meta doesnt update template

What’s the problem of this code?

  1. You incorrectly called get_page_by_path() whereby if you want to specify the post type (the third parameter), then you need to specify the second parameter as well which is the return type and defaults to OBJECT. So:

    // Wrong: Missing the return type (second parameter).
    // Or I mean, the third parameter "becomes" the second here.
    get_page_by_path( 'dneme1111', 'woocommerceareas' )
    
    // Correct.
    get_page_by_path( 'dneme1111', OBJECT, 'woocommerceareas' )
    

    But then, if you just want to get the ID of the newly inserted post via wp_insert_post(), you don’t need to call get_page_by_path() and instead, you could simply do something like:

    if ( $id = wp_insert_post( $post ) ) {
        // call update_post_meta() here
    }
    
  2. Note that the value of the page template meta has to be a file name like template-Blank.php (see note [1] below) and not the name of the template like Blank as in Template Name: Blank. Secondly, the template has to be in the theme folder, so the file name should be relative to that folder.

    So for example, if you have two page templates, one in the root theme folder and the other in a subfolder:

    your-theme/
      index.php
      style.css
      template-Blank.php - page template in root theme folder
      foo/
        template-bar.php - page template in a subfolder
      ...
    

    Then you would set the page template like so:

    $id = 123; // post ID
    
    // Correct: Use the file name.
    update_post_meta( $id, '_wp_page_template', 'template-Blank.php' );
    // Wrong.
    update_post_meta( $id, '_wp_page_template', 'Blank' );
    
    // Assuming that the template has "Template Name: Bar".
    // Correct: Use the file name and relative subfolder path in this case (foo/).
    update_post_meta( 456, '_wp_page_template', 'foo/template-bar.php' );
    // Wrong.
    update_post_meta( 456, '_wp_page_template', 'Bar' );
    

And if you’re actually trying to override the template with a custom template stored in the wp-content/plugins directory, then you would want to use the template_include hook instead of the _wp_page_template metadata:

// Example to override the singular template for all posts of the woocommerceareas post type.
add_filter( 'template_include', function ( $template ) {
    return is_singular( 'woocommerceareas' ) ? '/path/to/your/template-name.php' : $template;
} );

Or yes, you could also programmatically copy the custom template to the active theme folder and then use the template metadata to override the page template..


Note [1] For the default page template (e.g. page.php), you can use default as the meta value.