carawebs/wp-metadata-accessor

此包帮助从WordPress postmeta表获取数据。

1.0.4 2017-04-27 13:06 UTC

This package is auto-updated.

Last update: 2024-09-21 23:28:21 UTC


README

访问保存在postmeta表中的WordPress数据。

用法

运行

composer require carawebs/wp-metadata-accessor

示例:简单Postmeta字段数据

在主题文件中,实例化 Carawebs\DataAccessor\PostMetaData

然后,您可以通过PostMetaData::getField()方法轻松返回字段数据。

PostMetaData::getField( string $fieldName, string $filter)

示例用法

$postMeta = new Carawebs\DataAccessor\PostMetaData;

// returned content, unfiltered
$extra_content = $postMeta->getField('extra_content');

// returned content, filtered by `esc_html()`
$intro_text = $postMeta->getField('intro_text', 'text');

// returned content, filtered by `esc_html()`
$intro_text = $postMeta->getField('intro_text', 'esc_html');

// returned content filtered by WordPress 'the_content' filter
$extra_content = $postMeta->getContentField('extra_content');

返回数据

PostMetaData::getField()方法接受一个可选的字符串,表示字段类型作为第二个参数。这用于确定应用于返回数据的筛选方法。

如果您使用ACF字段,则不需要指定字段类型 - 这将自动确定。

返回数据处理

ACF重复字段数据

从post_meta表获取重复字段数据。按"行"将子字段数据分组到数组中。

ACF重复字段数据以记录集合的形式存储在postmeta表中。重复字段允许编辑器添加必要的子字段组。

重复字段键返回一个整数值,表示重复字段记录的数量 - 这允许每个记录有一个唯一的索引。子字段通过连接重复字段名称、索引和子字段名称来创建。这允许添加必要的项目。在键 => 值表示法中,数据集合看起来像这样

  • 重复字段:$repeater => $count
  • 第一个重复子字段:$first_subfield => $repeater . '_' . $index . '_' . $first_subfield
  • 第二个重复子字段:$second_subfield => $repeater . '_' . $index . '_' . $second_subfield // 等等

用法

$postMeta = new Carawebs\DataAccessor\PostMetaData;

$carouselSubfields = [
    'image' => ['image_ID', 'full'], // denotes an image ID subfield, image size to return
    'description' => 'text' // subfield name, filter to apply
];

$carouselData = $postMeta->getRepeaterField('slider', $carouselSubfields);

帖子到帖子关系

字段类型'relationship'获取一个帖子ID数组。

对于ACF关系字段,$this->postMeta->getField('related_posts') ...将返回ACF字段GUI中指定的类型。

否则,您可以传入一个字段名称并指定'relationship'类型和帖子ID数组:$this->postMeta->getField('related_posts', 'relationship')

如果您使用ACF字段并且字段'return_format'设置为返回对象,则将返回一个修改后的WordPress帖子对象,该对象具有表示帖子特色图片和永久链接的额外属性。此对象通过'carawebs/wp-metadata-accessor/post-object'进行筛选。要使用此筛选器,在活动主题中添加如下内容

add_filter('carawebs/wp-metadata-accessor/post-object', function($obj, $id) {
    $obj->newProperty = someFunction($id);
    return $obj;
}, 1, 2);