使用功能和页面模板创建wordpress虚拟页面

时间:2019-05-30 12:20:07

标签: php wordpress

我正在尝试在wordpress上创建虚拟联系人页面。所有必要的数据将存储在页面模板中。但是在我的函数中,我不知道如何链接到文件。

当用户访问 domain.com/contact 时,我想将他重定向到contact.php文件。

到目前为止,我可以使用该功能并显示$post->post_content = 'page template: contact.php';行中的内容,但我想显示templates/contact.php内的内容

add_filter( 'the_posts', 'generate_contact_page', -10 );

function generate_contact_page( $posts ) {
global $wp, $wp_query;

$url_slug = 'contact'; // URL slug of the contact page

if ( ! defined( 'CONTACT_PAGE' ) && ( strtolower( $wp->request ) == $url_slug ) ) {

    // stop interferring with other $posts arrays on this page (only works if the sidebar is rendered *after* the main page)
    define( 'CONTACT_PAGE', true );

    // create a contact virtual page
    $post = new stdClass;
    $post->post_author    = 1;
    $post->post_name      = $url_slug;
    $post->guid           = home_url() . '/' . $url_slug;
    $post->post_title     = 'Contact page';
    $post->post_content   = 'page template: contact.php';
    $post->ID             = -999;
    $post->post_type      = 'page';
    $post->post_status    = 'static';
    $post->comment_status = 'closed';
    $post->ping_status    = 'open';
    $post->comment_count  = 0;
    $post->post_date      = current_time( 'mysql' );
    $post->post_date_gmt  = current_time( 'mysql', 1 );
    $posts                = NULL;
    $posts[]              = $post;

    // make wpQuery believe this is a real page too
    $wp_query->is_page             = true;
    $wp_query->is_singular         = true;
    $wp_query->is_home             = false;
    $wp_query->is_archive          = false;
    $wp_query->is_category         = false;
    unset( $wp_query->query[ 'error' ] );
    $wp_query->query_vars[ 'error' ] = '';
    $wp_query->is_404 = false;
}

return $posts;
}

如何实现这样的目标?也许您知道更好的解决方案?

1 个答案:

答案 0 :(得分:0)

因此,对于模板输出,您可以尝试使用此功能

function get_template_output($slug = '', $name = '') {
    ob_start();
    get_template_part($lug, $name);
    return ob_get_clean();
}

然后分配内容,您将使用

$content = get_template_output('templates/', 'contact');