【问题标题】:Creating page with custom url / meta tags using Wordpress REST API使用 Wordpress REST API 创建带有自定义 url / 元标记的页面
【发布时间】:2018-12-30 07:56:44
【问题描述】:

我正在尝试在我的域上创建一个具有 url 'http://example.com/test/slug' 的自定义页面,但是 slug 似乎不支持斜杠(slug '/test/slug' 变成了 '/testslug') .是否可以使用 rest api 在自定义 url 上创建页面? 此外,我填充了“元”字典,但是创建的页面在标题中不包含元“描述”标签。如何正确创建自定义元标记?

import requests

url = 'http://example.com/wp-json/wp/v2/pages'
data = {'content': '<h2>test content</h2>',
 'meta': {'description': 'this is a test meta field'},
 'slug': 'test/slug',
 'status': 'publish',
 'title': 'test title'}

resp = requests.post(url, json=data, auth=('user','pass'), headers={'Content-Type':'application/json'})

【问题讨论】:

    标签: wordpress wordpress-rest-api


    【解决方案1】:

    slug 似乎不支持斜线(slug '/test/slug' 变成 进入“/testslug”)。

    是的,因为无论您使用 REST API 还是管理 UI 来创建页面,slug 都仅限于 字母数字 字符,加上破折号 (-) 和下划线 (_)。见https://developer.wordpress.org/rest-api/reference/pages/#schema-slug

    可以通过将remove_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 ); 添加到主题的functions.php 文件(或自定义插件)来消除限制;但是,默认情况下访问页面 (URL) 会引发 404(未找到)错误。有一些方法可以解决这个问题,但简而言之,您不应该删除 filter

    是否可以使用rest api在自定义url上创建页面?

    不,不是,默认情况下不是。

    但是,如果您希望 http://example.com/test/slug 提供/显示页面/帖子/等。无论是否通过 REST API 创建,您都可以使用自定义 URL 重写规则,例如通过add_rewrite_rule()

    创建的页面在 标题。如何正确创建自定义元标记?

    您需要注册元 key,在您的情况下是 description

    您可以使用 wp-includes/meta.php 中的register_meta() 函数注册它。

    description 元的示例:

    <?php
    // The object type. For custom post types, this is 'post';
    // for custom comment types, this is 'comment'. For user meta,
    // this is 'user'.
    $object_type = 'post'; // 'post' even for Pages
    $args1 = array( // Validate and sanitize the meta value.
        // Note: currently (4.7) one of 'string', 'boolean', 'integer',
        // 'number' must be used as 'type'. The default is 'string'.
        'type'         => 'string',
        // Shown in the schema for the meta key.
        'description'  => 'A meta key associated with a string meta value.',
        // Return a single value of the type.
        'single'       => true,
        // Show in the WP REST API response. Default: false.
        'show_in_rest' => true,
    );
    register_meta( $object_type, 'description', $args1 );
    

    要快速测试元 description 是否已成功注册以及是否可从 REST API 获得,请向 http://example.com/wp-json/wp/v2/pages/&lt;id&gt; 执行 GET 请求,其中 &lt;id&gt; 是页面 ID。

    【讨论】:

      【解决方案2】:

      首先,确保您的永久链接设置为“帖子名称”。

      这个可以在http://&lt;yoursite.com&gt;/wp-admin/options-permalink.php下配置

      我研究了“自定义永久链接”插件代码以了解如何回答这个问题,它保存了一个名为“custom_permalink”的元数据并执行大量的内部连接以使 WordPress 核心与“假”子插件一起工作。

      我想出了一个不同的解决方案。这里的技巧是创建一个假的父页面作为子页面的基本 URL。我是用 PHP 写的,因为我不懂 Python。

      <?php
      
      require_once('helpers.php');
      
      define('API_URL', 'http://temp.localhost');
      
      # Let's get all pages in an array
      $pages = curlGet(API_URL.'/wp-json/wp/v2/pages');
      
      # Your usual $args
      $args = array(
          'title' => 'API TEST',
          'status' => 'draft',
          'content' => 'content',
          'slug' => 'some/thing'
      );
      
      # We intercept it here, before sending to WordPress
      $args = maybe_add_parent($args);
      
      $response = curlPost( API_URL.'/wp-json/wp/v2/pages/', $args );
      
      /**
      *   Receives an $args array that would be sent to WordPress API and checks if we need to add a parent page
      */
      function maybe_add_parent(array $args) {
          if (array_key_exists('slug', $args)) {
              # Has parent?
              if (strpos($args['slug'], '/') !== false) {
                  $parent = explode('/', $args['slug']);
                  # For simplicity sake let's do it parent/chidren slugs only
                  if (count($parent) !== 2) {
                      die('This script can only run parent/children slugs');
                  }
                  $slug = array_pop($parent);
      
                  # Here, we will check the parent to see if it exists.
                  $parent_id = slug_exists($parent[0]);
                  if ($parent_id === false) {
                      # If it does not, it will create it and return it's ID
                      $parent_id = create_parent($parent[0]);
                  }
                  # Add parent ID to $args.
                  $args['parent'] = $parent_id;
                  # Rename the slug
                  $args['slug'] = $slug;
              }
          }
          return $args;
      }
      
      /**
      *   Checks if a given slug exists in $pages
      */
      function slug_exists(string $slug) {
          global $pages;
          foreach ($pages as $page) {
              # Checks if a "Parent" page with this slug exists
              if ($page['slug'] == $slug && $page['parent'] == 0) {
                  return true;
              }
          }
          return false;
      }
      
      /**
      *   Creates a parent page
      */
      function create_parent(string $slug) {
          $args = array(
              'title' => $slug,
              'status' => 'draft',
              'content' => '',
              'slug' => $slug
          );
          $response = json_decode(curlPost( API_URL.'/wp-json/wp/v2/pages/', $args ));
          return $response->id;
      }
      

      脚本执行以下操作:

      • 为网站上的所有页面发送 GET 请求。
      • 拦截将发送到 WordPress API 的 $args 数组。
      • 检查此 $args 是否包含格式为 parent/child 的 slug
      • 如果存在,检查parent页面是否存在
      • 如果没有,它将将此页面创建为草稿并返回其 ID
      • 如果父级已经存在,它只会返回它的 ID
      • 使用Parent ID,它会修改$args添加parent键并返回$args
      • 当 WordPress 看到该页面有父页面时,它会自动在 url 中添加它的 slug,如 parent/child

      有效:

      【讨论】:

        【解决方案3】:

        要获得所需的 URL 结构,最直接的方法是创建一个子页面,将现有页面作为其父页面引用。

        修改上面的示例:

        import requests
        
        url = 'http://example.com/wp-json/wp/v2/pages'
        parent_page = 43 # assuming that page with URL '/test' has id of 42
        data = {'content': '<h2>test content</h2>',
         'meta': {'description': 'this is a test meta field'},
         'slug': 'slug',
         'status': 'publish',
         'title': 'test title'
         'parent': parent_page} # <--
        
        resp = requests.post(url, json=data, auth=('user','pass'), headers={'Content-Type':'application/json'})
        

        会给你一个新的页面example.com/test/slug

        在 WordPress REST API 手册中对“创建页面”(POST /wp/v2/pages) 参数的引用:https://developer.wordpress.org/rest-api/reference/pages/#create-a-page

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-01-30
          • 2017-09-23
          • 2019-04-07
          • 2016-07-28
          • 1970-01-01
          • 1970-01-01
          • 2011-06-28
          相关资源
          最近更新 更多