WordPress载入自定义模板

    在我们自身的业务需求中,常常需要一些特殊的处理方式,仅仅靠自带函数并不能实现,这时我们便要自己封装函数解决

    locate_template( string|array $template_names, bool $load = false, bool $require_once = true, array $args = array() )
    PHP

    locate_template是检索存在的最高优先级模板文件的名称。

    参数说明

    $template_names(字符串|数组) (必需 )要顺序搜索的模板文件。

    $load(bool) (可选) 如果为true,则将在找到模板文件后对其进行加载。默认值:false

    $ require_once(bool) (可选) 是require_once还是require。如果$load为false,则无效。默认值:true

    $ args(array) (可选) 传递给模板的其他参数。默认值:array()

    我们的需求

    载入自定义邮件模板,且传递参数。

    在上一篇文章中,我们利用tijsverkoyen/css-to-inline-styles类,实现发送自定义邮件模板,但是在发送时我们如何携带参数呢?在查阅了Wordpress的官方文档后,我决定使用locate_template这个函数,当我一切准备就绪,发现在载入模板后所跟随的参数并没有生效,也不能获取。

    <?php 
    /** 
    * 加载模板文件 * 
    * @param string $slug 通用模板或子目录的slug名称 
    * @param string $name 自定义模板的名称 
    * @param bool $echo 立即输出或缓冲并返回 
    * @param array $param 包含在范围内的其他参数数组 
    */ 
    function topic_get_template_part($slug, $name, $echo = true, $params = array()){ 
        global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID; 
        do_action("get_template_part_{$slug}", $slug, $name); 
        $templates = array(); 
        if (isset($name)) { 
            $templates[] = "{$slug}/{$name}.php"; 
            $templates[] = "{$slug}-{$name}.php"; 
        } 
        $templates[] = "{$slug}.php"; 
        $template_file = locate_template($templates, false, false); 
        // 将查询变量和参数添加到域 
        if (is_array($wp_query->query_vars)) {
            extract($wp_query->query_vars, EXTR_SKIP);
        }
        extract($params, EXTR_SKIP);
        // 缓冲输出,如果echo为false,则返回
        if (!$echo) {
            ob_start();
        }
        require $template_file;
        if (!$echo) {
            return ob_get_clean();
        }
    }
    PHP

    通过自己封装函数,将array数组参数传递至模板

    $data = [
       'notify_message' => $notify_message,
       'comment_id' => $comment_ID,
    ];
    $html = topic_get_template_part(
       'templates/author/comment',
        '',
        false,
        array('data' => $data)
    );
    PHP

    Responses

    您的电子邮箱地址不会被公开。 必填项已用*标注

    Up Next:

    Wordpress email插件Topic Email

    Wordpress email插件Topic Email