【问题标题】:WordPress: Can you programmatically create page templates?WordPress:你能以编程方式创建页面模板吗?
【发布时间】:2018-10-05 09:50:07
【问题描述】:

我目前正在使用 WordPress API 为 WordPress 构建 React/Redux 主题。我需要将页面模板添加到我的主题中。我可以通过创建几乎空的文件来做到这一点:

<?php
/* Template Name: My Template */
?>

但我想以编程方式创建这些“页面模板”。

我需要的功能是能够在 WordPress CMS 中选择一个“页面模板”并将其写入 API。如果按上述方式创建“页面模板”,这将按预期运行。

这可能吗?

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    这可以使用theme_page_templates 过滤器来实现。

    CONST CUSTOM_PAGE_TEMPLATES = array(
      array('slug' => 'home', 'label' => 'Home'),
      array('slug' => 'content-page', 'label' => 'Content Page'),
      array('slug' => 'ordering', 'label' => 'Ordering'),
      array('slug' => 'reviews', 'label' => 'Reviews')
    ); 
    
    /**
     * Add file-less page templates to the page template dropdown 
     */
    add_filter('theme_page_templates', function($page_templates, $wp_theme, $post) {
      foreach(CUSTOM_PAGE_TEMPLATES as $template) {
        // Append if it doesn't already exists
        if (!isset($page_templates[$template['slug']])) {
          $page_templates[$template['slug']] = $template['label'];
        }
      }
      return $page_templates;
    }, PHP_INT_MAX, 3);
    

    【讨论】:

      猜你喜欢
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      相关资源
      最近更新 更多