这是一个简单的大纲,所以不要在生产中使用它,但这是一个工作示例。
定义模板并将其放置在templates/template-portfolio-template.php
在你的主题中。
<?php
/*
* Template Name: Portfolio Template
* Description: Page template to display portfolio custom post types
*/
echo \'This is the Portfolio Template!\';
接下来,您需要以编程方式生成帖子。
function programmatically_create_post($post_type = \'post\', $title, $content, $template_rel_path=\'\')
{
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
// Prep
$author_id = get_current_user_id();
$title = wp_strip_all_tags( $title ); // remove any junk
$slug = sanitize_title ($title); // converts to a usable post_name
$post_type = post_type_exists($post_type) ? $post_type : \'post\'; // make sure it exists
// If the page doesn\'t already exist, then create it
if( null == get_page_by_title( $title ) ) {
// Set the post ID so that we know the post was created successfully
$post_id = wp_insert_post(
array(
\'post_name\' => $slug,
\'post_title\' => $title,
\'post_content\' => $content,
\'post_type\' => $post_type,
\'post_author\' => $author_id,
\'comment_status\' => \'closed\',
\'ping_status\' => \'closed\',
\'post_status\' => \'publish\',
)
);
if( $post_id && $post_id > 0 && ! empty( $template_rel_path)) {
// make sure the template exists
$template_full_path = trailingslashit( get_stylesheet_directory() ) . $template_rel_path;
if( file_exists( $template_full_path )) {
// set the post meta data -- use relative path
update_post_meta( $post_id, \'_wp_page_template\', $template_rel_path );
}
}
// Otherwise, we\'ll stop
} else {
// Arbitrarily use -2 to indicate that the page with the title already exists
$post_id = -2;
} // end if
return $post_id;
} // end programmatically_create_post
然后测试它是否可以在没有模板的情况下工作。
add_action( \'init\', function(){
$template = \'templates/template-portfolio-template.php\';
$post_id_temp = programmatically_create_post( \'page\', \'My Page With a Template\', \'This is some sample content for the template! \' . timer_stop(4), $template );
$post_id_no_temp = programmatically_create_post( \'page\', \'My Page Without A Template\', \'This is some sample content! \' . timer_stop(4), \'\' );
if( -1 == $post_id_temp || -2 == $post_id_temp ) { // The post wasn\'t created or the page already exists
//...
} else {
$post = get_post($post_id_temp);
$url = get_permalink($post->ID); // your new page url
}
if( -1 == $post_id_no_temp || -2 == $post_id_no_temp ) { // The post wasn\'t created or the page already exists
//...
} else {
$post = get_post($post_id_no_temp);
$url = get_permalink($post->ID); // your new page url
}
} );