tgeorgel/wordplate-acf

使用面向对象PHP注册高级自定义字段

v2.2.0 2024-05-22 09:25 UTC

This package is auto-updated.

Last update: 2024-09-22 08:23:32 UTC


README

Extended ACF

扩展ACF

使用面向对象PHP注册高级自定义字段。

扩展ACF提供面向对象的API来注册ACF中的组和字段。如果您在主题中注册字段,可以在与其他开发者合作时安全地依赖版本控制。而且,您不必担心唯一字段键。

Build Status Monthly Downloads Latest Version

安装

在项目根目录中使用Composer安装此包。

composer require wordplate/acf

下载 Advanced Custom Fields Pro 插件并将其放入 pluginsmu-plugins 目录。访问WordPress仪表板并激活插件。

使用Composer安装ACF Pro(可选)

如果您想使用Composer安装 ACF Pro,您可以使用存储库功能。将以下代码片段添加到您的 composer.json 文件中。将 YOUR-ACF-KEY 替换为您的许可证密钥并运行 composer install

"repositories": [
    {
        "type": "package",
        "package": {
            "name": "wpackagist-plugin/advanced-custom-fields-pro",
            "type": "wordpress-plugin",
            "version": "5.12",
            "dist": {
                "url": "https://connect.advancedcustomfields.com/v2/plugins/download?p=pro&k=YOUR-ACF-KEY&t=5.12",
                "type": "zip"
            }
        }
    }
]

如果要将您的ACF密钥从 composer.json 文件中隐藏,您可以使用 private-composer-installer 插件。

用法

使用 register_extended_field_group() 函数注册一个新的字段组。它扩展了ACF插件中提供的默认 register_field_group() 函数。区别在于它将 key 值附加到字段组中。以下是一个字段组的示例。

use WordPlate\Acf\Fields\Image;
use WordPlate\Acf\Fields\Text;
use WordPlate\Acf\Location;

add_action('acf/init', function() {
    register_extended_field_group([
        'title' => 'About',
        'fields' => [
            Image::make('Image'),
            Text::make('Title'),
        ],
        'location' => [
            Location::where('post_type', 'page')
        ],
    ]);
});

注意:如果您正在运行PHP 7.4或更低版本,Composer将安装扩展ACF v11,上述代码片段将触发一个 未捕获的错误: 调用未定义的方法 WordPlate\Acf\Location::where() 错误,因为v11使用不同的语法。将 Location::where 替换为 Location::if 并继续。

设置

访问官方 ACF文档 了解有关字段组设置的更多信息。更多示例在示例目录中。

字段

所有字段都有其对应的类(除了克隆字段)。所有字段都必须有 label。如果没有提供 name,它将使用小写字母的 label 作为 namename 只能包含字母数字字符、下划线和破折号。

use WordPlate\Acf\Fields\Text;

Text::make('Title', 'heading')
    ->instructions('Add the text value')
    ->required();

基本字段

电子邮件 - 电子邮件字段 创建一个简单的电子邮件输入。

use WordPlate\Acf\Fields\Email;

Email::make('Email')
    ->instructions('Add the employees email address.')
    ->required();

数字 - 数字字段 创建一个简单的数字输入。

use WordPlate\Acf\Fields\Number;

Number::make('Age')
    ->instructions('Add the employees age.')
    ->min(18)
    ->max(65)
    ->required();

密码 - 密码字段 创建一个简单的密码输入。

use WordPlate\Acf\Fields\Password;

Password::make('Password')
    ->instructions('Add the employees secret pwned password.')
    ->required();

范围 - 范围字段 提供一个交互式体验来选择数值。

use WordPlate\Acf\Fields\Range;

Range::make('Rate')
    ->instructions('Add the employees completion rate.')
    ->min(0)
    ->max(100)
    ->step(10)
    ->required();

文本 - 文本字段创建一个简单的文本输入。

use WordPlate\Acf\Fields\Text;

Text::make('Name')
    ->instructions('Add the employees name.')
    ->characterLimit(100)
    ->required();

多行文本框 - 多行文本框字段创建一个简单的多行文本框。

use WordPlate\Acf\Fields\Textarea;

Textarea::make('Biography')
    ->instructions('Add the employees biography.')
    ->newLines('br') // br or wpautop
    ->characterLimit(2000)
    ->rows(10)
    ->required();

网址 - 网址字段创建一个简单的网址输入。

use WordPlate\Acf\Fields\Url;

Url::make('Website')
    ->instructions('Add the employees website link.')
    ->required();

选择字段

按钮组 - 按钮组字段创建一组单选按钮。

use WordPlate\Acf\Fields\ButtonGroup;

ButtonGroup::make('Color')
    ->instructions('Select the box shadow color.')
    ->choices([
        'cyan' => 'Cyan',
        'hotpink' => 'Hotpink',
    ])
    ->defaultValue('hotpink')
    ->returnFormat('value') // array, label or value (default)
    ->required();

复选框 - 复选框字段创建一组可勾选的输入项。

use WordPlate\Acf\Fields\Checkbox;

Checkbox::make('Color')
    ->instructions('Select the border color.')
    ->choices([
        'cyan' => 'Cyan',
        'hotpink' => 'Hotpink',
    ])
    ->defaultValue('cyan')
    ->returnFormat('value') // array, label or value (default)
    ->layout('horizontal') // vertical or horizontal
    ->required();

单选按钮 - 单选按钮字段创建一组可选择的输入项。

use WordPlate\Acf\Fields\RadioButton;

RadioButton::make('Color')
    ->instructions('Select the text color.')
    ->choices([
        'cyan' => 'Cyan',
        'hotpink' => 'Hotpink',
    ])
    ->defaultValue('hotpink')
    ->returnFormat('value') // array, label or value (default)
    ->required();

下拉选择 - 下拉选择字段创建一个下拉选择或多项选择输入。

use WordPlate\Acf\Fields\Select;

Select::make('Color')
    ->instructions('Select the background color.')
    ->choices([
        'cyan' => 'Cyan',
        'hotpink' => 'Hotpink',
    ])
    ->defaultValue('cyan')
    ->returnFormat('value') // array, label or value (default)
    ->allowMultiple()
    ->required();

是/否 - 是/否字段允许您选择1或0的值。

use WordPlate\Acf\Fields\TrueFalse;

TrueFalse::make('Social Media', 'display_social_media')
    ->instructions('Select whether to display social media links or not.')
    ->defaultValue(false)
    ->stylisedUi() // optional on and off text labels
    ->required();

内容字段

文件 - 文件字段允许上传和选择文件。

use WordPlate\Acf\Fields\File;

File::make('Resturant Menu', 'menu')
    ->instructions('Add the menu <strong>pdf</strong> file.')
    ->mimeTypes(['pdf'])
    ->library('all') // all or uploadedTo
    ->fileSize('400 KB', 5) // MB if entered as int
    ->returnFormat('array') // id, url or array (default)
    ->required();

相册 - 相册字段提供了一个简单直观的界面,用于管理一组图片。

use WordPlate\Acf\Fields\Gallery;

Gallery::make('Images')
    ->instructions('Add the gallery images.')
    ->mimeTypes(['jpg', 'jpeg', 'png'])
    ->height(500, 1400)
    ->width(1000, 2000)
    ->min(1)
    ->max(6)
    ->fileSize('400 KB', 5) // MB if entered as int
    ->library('all') // all or uploadedTo
    ->returnFormat('array') // id, url or array (default)
    ->previewSize('medium') // thumbnail, medium or large
    ->required();

图片 - 图片字段允许上传和选择图片。

use WordPlate\Acf\Fields\Image;

Image::make('Background Image')
    ->instructions('Add an image in at least 12000x100px and only in the formats <strong>jpg</strong>, <strong>jpeg</strong> or <strong>png</strong>.')
    ->mimeTypes(['jpg', 'jpeg', 'png'])
    ->height(500, 1400)
    ->width(1000, 2000)
    ->fileSize('400 KB', 5) // MB if entered as int
    ->library('all') // all or uploadedTo
    ->returnFormat('array') // id, url or array (default)
    ->previewSize('medium') // thumbnail, medium or large
    ->required();

oEmbed - oEmbed字段允许轻松嵌入视频、图片、推文、音频和其他内容。

use WordPlate\Acf\Fields\Oembed;

Oembed::make('Tweet')
    ->instructions('Add a tweet from Twitter.')
    ->required();

所见即所得 - 所见即所得字段创建一个完整的WordPress tinyMCE内容编辑器。

use WordPlate\Acf\Fields\WysiwygEditor;

WysiwygEditor::make('Content')
    ->instructions('Add the text content.')
    ->mediaUpload(false)
    ->tabs('visual')
    ->toolbar('simple') // toolbar name in snake_case
    ->required();

jQuery字段

颜色选择器 - 颜色选择器字段允许通过JavaScript弹出窗口选择颜色。

use WordPlate\Acf\Fields\ColorPicker;

ColorPicker::make('Text Color')
    ->instructions('Add the text color.')
    ->defaultValue('#4a9cff')
    ->required();

日期选择器 - 日期选择器字段创建一个jQuery日期选择弹出窗口。

use WordPlate\Acf\Fields\DatePicker;

DatePicker::make('Birthday')
    ->instructions('Add the employee\'s birthday.')
    ->displayFormat('d/m/Y')
    ->returnFormat('d/m/Y')
    ->required();

时间选择器 - 时间选择器字段创建一个jQuery时间选择弹出窗口。

use WordPlate\Acf\Fields\TimePicker;

TimePicker::make('Start Time', 'time')
    ->instructions('Add the start time.')
    ->displayFormat('H:i')
    ->returnFormat('H:i')
    ->required();

日期时间选择器 - 日期时间选择器字段创建一个jQuery日期和时间选择弹出窗口。

use WordPlate\Acf\Fields\DateTimePicker;

DateTimePicker::make('Event Date', 'date')
    ->instructions('Add the event\'s start date and time.')
    ->displayFormat('d-m-Y H:i')
    ->returnFormat('d-m-Y H:i')
    ->required();

谷歌地图 - 谷歌地图字段创建一个具有放置标记功能的交互式地图。

use WordPlate\Acf\Fields\GoogleMap;

GoogleMap::make('Address', 'address')
    ->instructions('Add the Google Map address.')
    ->center(57.456286, 18.377716)
    ->zoom(14)
    ->required();

布局字段

手风琴 - 手风琴字段用于将字段组织成可折叠的面板。

use WordPlate\Acf\Fields\Accordion;

Accordion::make('Address')
    ->open()
    ->multiExpand(),

// Allow accordion to remain open when other accordions are opened.
// Any field after this accordion will become a child.

Accordion::make('Endpoint')
    ->endpoint()
    ->multiExpand(),

// This field will not be visible, but will end the accordion above.
// Any fields added after this will not be a child to the accordion.

克隆 - 克隆字段允许您选择并显示现有的字段或组。此字段没有自定义字段类。相反,您需要在需要它的地方创建一个新文件,并使用require导入它。

occupation.php

use WordPlate\Acf\Fields\Text;

return Text::make('Occupation')
    ->instructions('Add the employees occupation.')
    ->required();

employee.php

register_extended_field_group([
    'fields' => [
        require __DIR__.'/fields/occupation.php';
    ]
]);

灵活内容 - 灵活内容字段作为一个空白画布,您可以添加任意数量的布局,并完全控制其顺序。

use WordPlate\Acf\Fields\FlexibleContent;
use WordPlate\Acf\Fields\Layout;
use WordPlate\Acf\Fields\Text;

FlexibleContent::make('Components', 'page_components')
    ->instructions('Add the employees occupation.')
    ->buttonLabel('Add a page component')
    ->layouts([
        Layout::make('Image')
            ->layout('block')
            ->fields([
                Text::make('Description')
            ])
    ])
    ->required();

分组 - 分组允许您创建一组子字段。

use WordPlate\Acf\Fields\Group;
use WordPlate\Acf\Fields\Image;
use WordPlate\Acf\Fields\Text;

Group::make('Hero')
    ->instructions('Add a hero block with title, content and image to the page.')
    ->fields([
        Text::make('Title'),
        Image::make('Background Image'),
    ])
    ->layout('row')
    ->required();

消息 - 消息字段允许您显示文本消息。

use WordPlate\Acf\Fields\Message;

Message::make('Message')
    ->message('George. One point twenty-one gigawatts.')
    ->escapeHtml();

重复器 - 重复器字段 允许您创建一组子字段,这些字段可以在编辑内容时重复使用!

use WordPlate\Acf\Fields\Image;
use WordPlate\Acf\Fields\Repeater;
use WordPlate\Acf\Fields\Text;

Repeater::make('Employees')
    ->instructions('Add the employees.')
    ->fields([
        Text::make('Name'),
        Image::make('Profile Picture'),
    ])
    ->min(2)
    ->collapsed('name')
    ->buttonLabel('Add employee')
    ->layout('table') // block, row or table
    ->required();

标签页 - 标签页字段 用于将字段分组到标签页部分。在添加 acf_tab 后添加的任何字段或组都将成为该标签页的子项。在标签页上设置 'endpoint' 为 true 将创建一个新的标签页组。

use WordPlate\Acf\Fields\Tab;

Tab::make('Tab 1'),
Tab::make('Tab 2'),
Tab::make('Tab 3')
    ->placement('top') // top or left
    ->endpoint(), // This will make a break in the tabs and create a new group of tabs.

关系字段

链接 - 链接字段 提供了一种简单的方式来选择或定义链接(URL、标题、目标)。

use WordPlate\Acf\Fields\Link;

Link::make('Read More Link')
    ->returnFormat('array') // url or array (default)
    ->required();

页面链接 - 页面链接字段 允许选择 1 个或多个帖子、页面或自定义帖子类型。

use WordPlate\Acf\Fields\PageLink;

PageLink::make('Contact Link')
    ->postTypes(['contact'])
    ->taxonomies(['category:city'])
    ->allowArchives() // optionally pass 'false' to disallow archives
    ->allowNull()
    ->allowMultiple()
    ->required();

帖子对象 - 帖子对象字段 创建一个选择字段,其中的选项是您的页面 + 帖子 + 自定义帖子类型。

use WordPlate\Acf\Fields\PostObject;

PostObject::make('Animal')
    ->instructions('Select an animal')
    ->postTypes(['animal'])
    ->allowNull()
    ->allowMultiple()
    ->returnFormat('object') // id or object (default)
    ->required();

关系 - 关系字段 创建了一个非常吸引人的帖子对象字段的版本。

use WordPlate\Acf\Fields\Relationship;

Relationship::make('Contacts')
    ->instructions('Add the contacts.')
    ->postTypes(['contact'])
    ->filters([
        'search',
        'post_type',
        'taxonomy'
    ])
    ->elements(['featured_image'])
    ->min(3)
    ->max(6)
    ->returnFormat('object') // id or object (default)
    ->required();

分类法 - 分类法字段 允许选择 1 个或多个分类术语。

use WordPlate\Acf\Fields\Taxonomy;

Taxonomy::make('Cinemas')
    ->instructions('Select one or more cinema terms.')
    ->taxonomy('cinema')
    ->appearance('checkbox') // checkbox, multi_select, radio or select
    ->addTerm(true) // Allow new terms to be created whilst editing (true or false)
    ->loadTerms(true) // Load value from posts terms (true or false)
    ->saveTerms(true) // Connect selected terms to the post (true or false)
    ->returnFormat('id'); // object or id (default)

用户 - 用户字段创建一个选择字段,用于您所有的用户。

use WordPlate\Acf\Fields\User;

User::make('User')
    ->roles([
        'administrator',
        'author'
    ])
    ->returnFormat('array'); // id, object or array (default)

// Available roles are administrator, author, subscriber, contributor and editor. Default is no filter.

位置

位置类允许您在不使用 nameoperatorvalue 键的情况下编写 自定义位置规则。如果没有提供 operator,它将使用 operator 作为 value

use WordPlate\Acf\Location;

Location::where('post_type', 'post')->and('post_type', '!=', 'post');

注意:版本 12 中 if 方法已重命名为 where

条件逻辑

条件类帮助您编写条件逻辑 而不必知道 字段键。

use WordPlate\Acf\ConditionalLogic;
use WordPlate\Acf\Fields\File;
use WordPlate\Acf\Fields\Select;
use WordPlate\Acf\Fields\Url;

Select::make('Type')
    ->choices([
        'document' => 'Document',
        'link' => 'Link to resource',
    ]),
File::make('Document', 'file')
    ->conditionalLogic([
        ConditionalLogic::where('type', '==', 'document') // available operators are ==, !=, >, <, ==pattern, ==contains, ==empty, !=empty
    ]),
Url::make('Link', 'url')
    ->conditionalLogic([
        ConditionalLogic::where('type', '==', 'link')
    ]),

自定义配置

如果您想为字段添加自定义设置,可以扩展此库中可用的字段类。

namespace App\Fields;

use WordPlate\Acf\Fields\Select as Field;

class Select extends Field
{
    public function myNewSetting(string $value): self
    {
        $this->settings['my-new-settings'] = $value;

        return $this;
    }
}

自定义字段

如果您想创建自定义字段类,可以扩展 基本字段类。您还可以导入 可用的设置特质,以便添加如 required()intstructions() 这样的常用方法。

namespace App\Fields;

use WordPlate\Acf\Fields\Field;
use WordPlate\Acf\Fields\Settings\Instructions;
use WordPlate\Acf\Fields\Settings\Required;

class OpenStreetMap extends Field
{
    use Instructions;
    use Required;

    protected $type = 'open_street_map';

    public function latitude(float $latitude): static
    {
        $this->settings['latitude'] = $latitude;

        return $this;
    }

    public function longitude(float $longitude): static
    {
        $this->settings['longitude'] = $longitude;

        return $this;
    }

    public function zoom(float $zoom): static
    {
        $this->settings['zoom'] = $zoom;

        return $this;
    }
}

准备就绪后,您可以像使用此库中任何其他字段一样使用您的字段。

use App\Fields\OpenStreetMap;

OpenStreetMap::make('Map')
    ->latitude(56.474)
    ->longitude(11.863)
    ->zoom(10);

升级

  • 2.2.0translate() 方法现在期望一个枚举值而不是一个字符串。
use WordPlate\Acf\Enums\TranslationMode;

-Text::make('Content')->translate('copy_once');
+Text::make('Content')->translate(TranslationMode::COPY_ONCE);