如何在wordpress中动态分配页面模板

Vid*_*a L 4 php wordpress templates

我有一个动态创建的 WordPress 页面

$my_post = array(
        'post_title' => 'page-for-download',
        'post_content' => '',
        'post_status' => 'publish',
        'post_author' => 1,
        'post_type' => 'page'

    );
Run Code Online (Sandbox Code Playgroud)

现在我的问题是如何动态地将页面模板分配给这个页面

Nik*_*lov 7

WordPress 将页面模板保存在帖子元条目中(名为_wp_page_template)。创建页面后,您应该执行以下操作:

update_post_meta( $new_post_id, '_wp_page_template', 'custom-template.php' );
Run Code Online (Sandbox Code Playgroud)

$new_post_id结果在哪里wp_insert_post()(我假设这是您用来创建新帖子的内容)。请注意,您可能需要检查您是否有实际的 id(wp_insert_post()如果无法创建新帖子,默认情况下将返回 false)。

您可以在 WordPress codex 页面Function Reference/wp insert post参数部分的第一个注释中看到该信息