dqcqcqwq38860 2019-05-30 12:20
浏览 79

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

I'm trying to create a virtual contact page on wordpress. All the necessary data will be stored in a page template. But in my function I don't know how to link to the file.

When the user does to domain.com/contact I would like to redirect him to the contact.php file.

So far I got this function to work and show content from this line $post->post_content = 'page template: contact.php'; but I would like to show the content from 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;
}

How can I achieve something like this? Maybe you know a better solution ?

  • 写回答

1条回答 默认 最新

  • dongpi2503 2019-05-30 12:45
    关注

    So for template output you can try this function

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

    And then to assign content you will use

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大