hard-g/cpt-tax

WordPress 库,为给定的自定义文章类型中的每个条目创建一个对应的分类术语。适用于模拟文章之间的关联。

v1.0.1 2023-05-26 15:24 UTC

This package is auto-updated.

Last update: 2024-08-26 18:19:25 UTC


README

这是一个专为WordPress插件使用而设计的库。该库允许您确保自定义文章类型中的每篇文章都有一个对应的自定义分类术语。

用例概述

这种映射的目的是什么?WordPress 本身不支持文章之间的直接关联。多对多关系仅存在于分类术语和文章之间。这个库为这种限制提供了一种解决方案。

例如,假设您正在构建一个关于电影的WordPress网站。您有三个自定义文章类型:电影、奖项和演员。作为系统的一部分,您希望能够将演员与电影和奖项相关联。此外,这些关系必须是多对多的:单个演员可以与多部电影相关联,而单一电影可能被许多演员相关联。

在您的插件或主题中,您将注册一个与演员对应的分类。然后,告诉这个库在分类(例如,actor_tax)和文章类型(例如,actor_pt)之间创建一个链接

\HardG\CptTax\Registry::register( 'actors', 'actor_pt', 'actor_tax' );

actor_pt 文章类型中的每篇文章都将在 actor_tax 分类中有一个对应的术语。然后,您可以使用WP的分类工具将演员与电影关联起来

// Fetch the term ID corresponding to the Actor post.
$actor_term_id = \HardG\CptTax\Registry::get_term_id_for_post_id( 'actors', $actor_post_id );

wp_set_object_terms( $movie_post_id, [ $actor_term_id ], 'actor_tax', true );

稍后,如果您想要查询与演员相关联的电影,您将使用类似的技术

// Fetch the term ID corresponding to the Actor post.
$actor_term_id = \HardG\CptTax\Registry::get_term_id_for_post_id( 'actors', $actor_post_id );

$movies_with_actor = get_posts(
  [
    'post_type' => 'movie_pt',
    'tax_query' => [
      [
        'taxonomy' => 'actor_tax',
	'terms'    => $actor_term_id,
      ]
    ],
  ]
);

同样,如果您想要显示与特定电影相关联的演员列表

$actor_posts = array_map(
  function( $actor_term ) {
    $actor_post_id = \HardG\CptTax\Registry::get_post_id_for_term_id( 'actors', $actor_term->term_id );
    return get_post( $actor_post_id );
  },
  wp_get_object_terms( $movie_post_id, 'actor_tax' );
);

方法

\HardG\CptTax\Registry::register( $link_key, $post_type, $taxonomy )

设置文章类型和分类之间的链接。在注册了分类和文章类型之后不久调用此方法。`$link_key` 是此“对”的唯一标识符,您将使用它来引用此对。

\HardG\CptTax\Registry::get_post_id_for_term_id( $link_key, $term_id )

获取与给定链接术语关联的文章的ID。

\HardG\CptTax\Registry::get_term_id_for_post_id( $link_key, $post_id )

获取与给定链接文章关联的术语的ID。

提示

此库不会为您注册映射的分类。您必须自行完成此操作。在许多情况下,此分类仅用于在数据库中提供链接,因此建议将该分类设置为非公开

register_taxonomy(
  'my_taxonomy',
  $my_post_types,
  [
    // ...
    'public' => false,
    'show_ui' => false, // Unless you want to be able to see it for diagnostic purposes in the Dashboard
    'show_in_rest' => false,
    // ...
  ]
);

如果您启用了UI,您可能希望禁用新术语的创建(所有术语创建都由库处理),同时仍然允许在UI中将术语分配给文章

// ...
'capabilities' => [
  'manage_terms' => 'do_not_allow',
  'edit_terms'   => 'do_not_allow',
  'delete_terms' => 'do_not_allow',
],
// ...