0

How we can provide page_template path in custom plugin using WordPress?

I given a path in page_template='templatepage/checkoutpage.php' as array of post.Inserting post data by wp_insertpost() function.But page_template value of path is not triggered and not displaying the php template file.I created a custom template page and it's not triggering.

Please give suggestions for my question.

1
  • Where is the file templatepage/checkoutpage.php located? In your active theme or in a a plugin? Are you trying to apply this template to a page or to a custom post type?
    – Pat J
    May 8 at 21:14

1 Answer 1

0

Here is some code that inserts a post using wp_insert_post. In the process, it specifies the page template for the post using the page_template parameter. The path to the template is relative to theme directory.

function wpse415873_insert_page(){
  
  $post = array(
    'post_content'          => 'This page was generated with wp_insert_post',
    'post_title'            => 'WPSE415873 Test Title',
    'page_template'         => 'page-templates/full-width.php',
    'post_type'             => 'post'
  );
  
  global $wpdb;
  $query = $wpdb->prepare( 
    "SELECT * 
    FROM $wpdb->posts 
    WHERE post_title=%s
    AND NOT post_status=%s
    AND NOT post_status=%s", 
    "WPSE415873 Test Title", 
    'inherit', 
    'trash' 
  );

  $posts = $wpdb->get_results( $query );
  
  if ( !count($posts) ){
    wp_insert_post( $post );
  }
}
add_action( 'init', 'wpse415873_insert_page' );

Make sure the Template Post Type declaration in the file header of your page template includes the type of post you are inserting. For instance, my full-width.php template has the following header which allows it to apply to both posts and pages:

<?php
/**
 * Template Name: Full-width
 * Template Post Type: post, page
*/

The reason for the database query is to figure out if the post already exists in some form other than a trashed post or revision. If so, we probably don't want to insert it again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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