Giter Club home page Giter Club logo

extended-acf's Introduction

Extended ACF

Extended ACF

Register advanced custom fields with object-oriented PHP.

Extended ACF provides an object-oriented API to register groups and fields with ACF. If you register fields in your theme, you can safely rely on version control when working with other developers. Oh, you don't have to worry about unique field keys.

Build Status Monthly Downloads Latest Version

Installation

Require this package, with Composer, in the root directory of your project.

composer require vinkla/extended-acf

To install the Advanced Custom Fields Pro plugin, download and place it in either the plugins or mu-plugins directory. After that, activate the plugin in the WordPress dashboard.

Learn more about installing ACF PRO using Composer.

Usage

To register a new field group, use the register_extended_field_group() function. This extends the default register_field_group() function from the ACF plugin. The key value is appended to field groups and fields. Here's an example of a field group.

use Extended\ACF\Fields\Image;
use Extended\ACF\Fields\Text;
use Extended\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')
        ],
    ]);
});

Settings

For detailed information on field group settings, please consult the official ACF documentation. You can also find more examples in the examples directory.

Fields

All fields, except the clone field, have a corresponding class. Each field needs a label. If no name is specified, the label will be used as the name in snake_case. The name can only contain alphanumeric characters and underscores.

use Extended\ACF\Fields\Text;

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

Most fields have the methods default, required, and wrapper. The basic fields also have the methods prepend, append, placeholder, readOnly, and disabled. Please also check the non-standard methods mentioned in the non-standards section.

Basic

Email - The email field creates a simple email input.

use Extended\ACF\Fields\Email;

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

Number - The number field creates a simple number input.

use Extended\ACF\Fields\Number;

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

Password - The password field creates a simple password input.

use Extended\ACF\Fields\Password;

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

Range - The range field provides an interactive experience for selecting a numerical value.

use Extended\ACF\Fields\Range;

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

Text - The text field creates a simple text input.

use Extended\ACF\Fields\Text;

Text::make('Name')
    ->helperText('Add the employees name.')
    ->maxLength(100)
    ->required()

Textarea - The textarea field creates a simple textarea.

use Extended\ACF\Fields\Textarea;

Textarea::make('Biography')
    ->helperText('Add the employees biography.')
    ->newLines('br') // br, wpautop
    ->maxLength(2000)
    ->rows(10)
    ->required()

URL - The URL field creates a simple uRL input.

use Extended\ACF\Fields\URL;

URL::make('Website')
    ->helperText('Add the employees website link.')
    ->required()

Content

File - The file field allows a file to be uploaded and selected.

use Extended\ACF\Fields\File;

File::make('Resturant Menu', 'menu')
    ->helperText('Add the menu **pdf** file.')
    ->acceptedFileTypes(['pdf'])
    ->library('all') // all, uploadedTo
    ->minSize('400 KB')
    ->maxSize(5) // MB if entered as int
    ->format('array') // id, url, array (default)
    ->required()

Gallery - The gallery field provides a simple and intuitive interface for managing a collection of images.

use Extended\ACF\Fields\Gallery;

Gallery::make('Images')
    ->helperText('Add the gallery images.')
    ->acceptedFileTypes(['jpg', 'jpeg', 'png'])
    ->minHeight(500)
    ->maxHeight(1400)
    ->minWidth(1000)
    ->maxWidth(2000)
    ->minFiles(1)
    ->maxFiles(6)
    ->minSize('400 KB')
    ->maxSize(5) // MB if entered as int
    ->library('all') // all, uploadedTo
    ->format('array') // id, url, array (default)
    ->previewSize('medium') // thumbnail, medium, large
    ->prependFiles()
    ->required()

Image - The image field allows an image to be uploaded and selected.

use Extended\ACF\Fields\Image;

Image::make('Background Image')
    ->helperText('Add an image in at least 12000x100px and only in the formats **jpg**, **jpeg** or **png**.')
    ->acceptedFileTypes(['jpg', 'jpeg', 'png'])
    ->minHeight(500)
    ->maxHeight(1400)
    ->minWidth(1000)
    ->maxWidth(2000)
    ->minSize('400 KB')
    ->maxSize(5) // MB if entered as int
    ->library('all') // all, uploadedTo
    ->format('array') // id, url, array (default)
    ->previewSize('medium') // thumbnail, medium, large
    ->required()

Oembed - The oEmbed field allows an easy way to embed videos, images, tweets, audio, and other content.

use Extended\ACF\Fields\Oembed;

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

WYSIWYG - The WYSIWYG field creates a full WordPress tinyMCE content editor.

use Extended\ACF\Fields\WYSIWYGEditor;

WYSIWYGEditor::make('Content')
    ->helperText('Add the text content.')
    ->tabs('visual') // all, text, visual (default)
    ->toolbar(['bold', 'italic', 'link']) // aligncenter, alignleft, alignright, blockquote, bold, bullist, charmap, forecolor, formatselect, fullscreen, hr, indent, italic, link, numlist, outdent, pastetext, redo, removeformat, spellchecker, strikethrough, underline, undo, wp_adv, wp_help, wp_more
    ->disableMediaUpload()
    ->lazyLoad()
    ->required()

Choice

Button Group - The button group field creates a list of radio buttons.

use Extended\ACF\Fields\ButtonGroup;

ButtonGroup::make('Color')
    ->helperText('Select the box shadow color.')
    ->choices(['Forest Green', 'Sky Blue']) // ['forest_green' => 'Forest Green', 'sky_blue' => 'Sky Blue']
    ->default('forest_green')
    ->format('value') // array, label, value (default)
    ->required()

Checkbox - The checkbox field creates a list of tick-able inputs.

use Extended\ACF\Fields\Checkbox;

Checkbox::make('Color')
    ->helperText('Select the border color.')
    ->choices(['Forest Green', 'Sky Blue']) // ['forest_green' => 'Forest Green', 'sky_blue' => 'Sky Blue']
    ->default('forest_green')
    ->format('value') // array, label, value (default)
    ->layout('horizontal') // vertical, horizontal
    ->required()

Radio Button - The radio button field creates a list of select-able inputs.

use Extended\ACF\Fields\RadioButton;

RadioButton::make('Color')
    ->helperText('Select the text color.')
    ->choices(['Forest Green', 'Sky Blue']) // ['forest_green' => 'Forest Green', 'sky_blue' => 'Sky Blue']
    ->default('forest_green')
    ->format('value') // array, label, value (default)
    ->required()

Select - The select field creates a drop down select or multiple select input.

use Extended\ACF\Fields\Select;

Select::make('Color')
    ->helperText('Select the background color.')
    ->choices(['Forest Green', 'Sky Blue']) // ['forest_green' => 'Forest Green', 'sky_blue' => 'Sky Blue']
    ->default('forest_green')
    ->format('value') // array, label, value (default)
    ->multiple()
    ->nullable()
    ->stylized() // stylized checkbox using select2
    ->lazyLoad() // use AJAX to lazy load choices
    ->required()

True False - The true / false field allows you to select a value that is either 1 or 0.

use Extended\ACF\Fields\TrueFalse;

TrueFalse::make('Social Media', 'display_social_media')
    ->helperText('Select whether to display social media links or not.')
    ->default(false)
    ->stylized(on: 'Yes', off: 'No') // optional on and off text labels
    ->required()

Relational

Link - The link field provides a simple way to select or define a link (url, title, target).

use Extended\ACF\Fields\Link;

Link::make('Read More Link')
    ->format('array') // url, array (default)
    ->required()

Page Link - The page link field allows the selection of 1 or more posts, pages or custom post types.

use Extended\ACF\Fields\PageLink;

PageLink::make('Contact Link')
    ->postTypes(['contact'])
    ->postStatus(['publish']) // draft, future, pending, private, publish
    ->taxonomies(['category:city'])
    ->disableArchives()
    ->nullabel()
    ->multiple()
    ->required()

Post Object - The post object field creates a select field where the choices are your pages + posts + custom post types.

use Extended\ACF\Fields\PostObject;

PostObject::make('Animal')
    ->helperText('Select an animal')
    ->postTypes(['animal'])
    ->postStatus(['publish']) // draft, future, pending, private, publish
    ->nullabel()
    ->multiple()
    ->format('object') // id, object (default)
    ->required()

Relationship - The relationship field creates a very attractive version of the post object field.

use Extended\ACF\Fields\Relationship;

Relationship::make('Contacts')
    ->helperText('Add the contacts.')
    ->postTypes(['contact'])
    ->postStatus(['publish']) // draft, future, pending, private, publish
    ->filters([
        'search', 
        'post_type',
        'taxonomy'
    ])
    ->elements(['featured_image'])
    ->minPosts(3)
    ->maxPosts(6)
    ->format('object') // id, object (default)
    ->required()

Taxonomy - The taxonomy field allows the selection of 1 or more taxonomy terms.

use Extended\ACF\Fields\Taxonomy;

Taxonomy::make('Cinemas')
    ->helperText('Select one or more cinema terms.')
    ->taxonomy('cinema')
    ->appearance('checkbox') // checkbox, multi_select, radio, select
    ->format('id') // object, id (default)
    ->create(false) // false or true (default)
    ->load(true) // true or false (default)
    ->save(true) // true or false (default)x
    ->format('id'), // object or id (default)

User - The user field creates a select field for all your users.

use Extended\ACF\Fields\User;

User::make('User')
    ->roles(['administrator', 'editor']) // administrator, author, contributor, editor, subscriber
    ->format('array'), // id, object, array (default)

Advanced

Color Picker - The color picker field allows a color to be selected via a JavaScript popup.

use Extended\ACF\Fields\ColorPicker;

ColorPicker::make('Text Color')
    ->helperText('Add the text color.')
    ->default('#4a9cff')
    ->opacity()
    ->format('string') // array, string (default)
    ->required()

Date Picker - The date picker field creates a jQuery date selection popup.

use Extended\ACF\Fields\DatePicker;

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

Icon Picker - The icon picker field allows you to easily select a Dashicon, a Media Library image, or a URL for an image or SVG.

use Extended\ACF\Fields\IconPicker;

IconPicker::make('Icon')
    ->helperText('Add the icon.')
    ->format('string') // array, string (default)
    ->tabs(['dashicons']) // [dashicons, media_library, url] (default)
    ->required()

Time Picker - The time picker field creates a jQuery time selection popup.

use Extended\ACF\Fields\TimePicker;

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

Date Time Picker - The date time picker field creates a jQuery date & time selection popup.

use Extended\ACF\Fields\DateTimePicker;

DateTimePicker::make('Event Date', 'date')
    ->helperText('Add the event\'s start date and time.')
    ->displayFormat('d-m-Y H:i')
    ->format('d-m-Y H:i')
    ->firstDayOfWeek(1) // Sunday is 0, Monday is 1, or use `weekStartsOnMonday` or `weekStartsOnSunday`
    ->required()

Google Map - The Google Map field creates an interactive map with the ability to place a marker.

use Extended\ACF\Fields\GoogleMap;

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

Layout

Accordion - The accordion field is used to organize fields into collapsible panels.

use Extended\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.

Clone - The clone field enables you to choose and showcase pre-existing fields or groups. This field does not possess a custom field class. Instead, you can create a new file for your field and import it using the require statement whenever necessary.

// fields/email.php
use Extended\ACF\Fields\Email;

return Email::make('Email')->required();

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

Flexible Content - The flexible content field acts as a blank canvas to which you can add an unlimited number of layouts with full control over the order.

use Extended\ACF\Fields\FlexibleContent;
use Extended\ACF\Fields\Layout;
use Extended\ACF\Fields\Text;

FlexibleContent::make('Blocks')
    ->helperText('Add the page blocks.')
    ->button('Add Component')
    ->layouts([
        Layout::make('Image')
            ->layout('block')
            ->fields([
                Text::make('Description')
            ])
    ])
    ->minLayouts(1)
    ->maxLayouts(10)
    ->required()

Group - The group allows you to create a group of sub fields.

use Extended\ACF\Fields\Group;
use Extended\ACF\Fields\Image;
use Extended\ACF\Fields\Text;

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

Message - The message fields allows you to display a text message.

use Extended\ACF\Fields\Message;

Message::make('Heading')
    ->body('George. One point twenty-one gigawatts.')
    ->escapeHtml(),

Repeater - The repeater field allows you to create a set of sub fields which can be repeated again and again whilst editing content!

use Extended\ACF\Fields\Image;
use Extended\ACF\Fields\Repeater;
use Extended\ACF\Fields\Text;

Repeater::make('Employees')
    ->helperText('Add the employees.')
    ->fields([
        Text::make('Name'),
        Image::make('Profile Picture'),
    ])
    ->minRows(2)
    ->maxRows(10)
    ->collapsed('name')
    ->button('Add employee')
    ->paginated(10)
    ->layout('table') // block, row, table
    ->required()

Tab - The tab field groups fields into tabbed sections. Fields or groups added after a tab become its children. Enabling endpoint on a tab creates a new group of tabs.

use Extended\ACF\Fields\Tab;

Tab::make('Tab 1'),
Tab::make('Tab 2'),
Tab::make('Tab 3')
    ->placement('top') // top, left
    ->selected() // specify which tab should be selected by default
    ->endpoint(), // This will make a break in the tabs and create a new group of tabs

Location

The Location class allows you to write custom location rules without specifying the name, operator, and value keys. If no operator is provided, it will use the operator as the value. For additional details on custom location rules, please visit this link.

use Extended\ACF\Location;

Location::where('post_type', 'post')->and('post_type', '!=', 'post') // available operators: ==, !=

Note

The if method was renamed to where in version 12, see the upgrade guide.

Conditional Logic

The conditional class helps you write conditional logic without knowing the field keys.

use Extended\ACF\ConditionalLogic;
use Extended\ACF\Fields\File;
use Extended\ACF\Fields\Select;
use Extended\ACF\Fields\URL;
use Extended\ACF\Fields\Textarea;
use Extended\ACF\Fields\Text;

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

// "and" condition
Textarea::make('Embed Code')
    ->conditionalLogic([
        ConditionalLogic::where('type', '!=', 'document')->and('type', '!=', 'link')
    ]),

// use multiple conditional logic for "or" condition
Text::make('Title')
    ->conditionalLogic([
        ConditionalLogic::where('type', '!=', 'document'),
        ConditionalLogic::where('type', '!=', 'link')
    ]),

// conditional logic that relies on another field from a different field group
Text::make('Sub Title')
    ->conditionalLogic([
      ConditionalLogic::where(
        group: 'other-group',
        name: 'enable_highlight', 
        operator: '==', 
        value: 'on', 
      )
    ]),

Non-standards

helperText

The helperText method supports Markdown for the elements listed below.

Text::make('Title')
    ->helperText('__strong__ **strong** _italic_ *italic* `code` [link](https://example.com)')

column

The column property is not a standard in ACF. It is used as a shorthand for setting the width of the field wrapper. You can provide a number between 0 and 100 as its value.

Text::make('Text')
    ->column(50) // shorthand for ->wrapper(['width' => 50])

dd and dump

The dd and dump methods are non-standard and not available in ACF. These methods are used for debugging.

Text::make('Name')
    ->dd()
    ->dump()

To use the dd and dump methods, you need to install symfony/var-dumper.

composer require symfony/var-dumper --dev

key

The key method enables you to define a custom field key. The key should consist of alphanumeric characters and underscores, and must be prefixed with either field_ or layout_.

Text::make('Text')
    ->key('field_123abc')

You can use the key argument to provide a custom field key in conditional logic.

ConditionalLogic::where(
  name: 'color', 
  operator: '==', 
  value: 'red'
  key: 'field_123abc', 
)

Important

Avoid using custom field keys unless you thoroughly understand them. The field keys are automatically generated when you use the register_extended_field_group function.

withSettings

The withSettings method overwrites any existing settings on the field when you want to add custom settings.

Text::make('Name')
	->withSettings(['my-new-setting' => 'value'])
	->required()

Another option for adding custom settings is to extend the field classes provided in the package. Please refer to the custom fields section.

namespace App\Fields;

use Extended\ACF\Fields\Select as Field;

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

        return $this;
    }
}

Custom Fields

To create custom field classes, you can extend the base field class. Additionally, you can import available setting traits to add common methods like required and helperText.

namespace App\Fields;

use Extended\ACF\Fields\Field;
use Extended\ACF\Fields\Settings\HelperText;
use Extended\ACF\Fields\Settings\Required;

class OpenStreetMap extends Field
{
    use HelperText;
    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;
    }
}

When you're ready, you can import and use your field just like any other field in this library.

use App\Fields\OpenStreetMap;

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

Upgrade Guide

The upgrade guide provides information about the breaking changes in the package, now named vinkla/extended-acf. If you have version 12 or lower, you can update by replacing the package name in your composer.json file. This ensures that everything works as expected and you receive updates.

-"wordplate/acf": "^12.0",
+"vinkla/extended-acf": "^12.0"

14

The Url class has been renamed to URL.

-use Extended\ACF\Fields\Url;
+use Extended\ACF\Fields\URL;

-Url::make('GitHub URL')
+URL::make('GitHub URL')

The WysiwygEditor class has been renamed to WYSIWYGEditor.

-use Extended\ACF\Fields\WysiwygEditor;
+use Extended\ACF\Fields\WYSIWYGEditor;

-WysiwygEditor::make('Content')
+WYSIWYGEditor::make('Content')

The defaultValue method has been renamed to default.

-Text::make('Name')->defaultValue('Jeffrey Way')
+Text::make('Name')->default('Jeffrey Way')

The instructions method has been renamed to helperText.

-Text::make('Title')->instructions('Add the title text.')
+Text::make('Title')->helperText('Add the title text.')

The allowMultiple method has been renamed to multiple.

-Select::make('Colors')->allowMultiple()
+Select::make('Colors')->multiple()

The allowNull method has been renamed to nullable.

-Select::make('Features')->allowNull()
+Select::make('Features')->nullable()

The characterLimit method has been renamed to maxLength.

-Textarea::make('Description')->characterLimit(100)
+Textarea::make('Description')->maxLength(100)

The pagination method has been renamed to paginated.

-Repeater::make('Dogs')->pagination(10)
+Repeater::make('Dogs')->paginated(10)

The buttonLabel method has been renamed to button.

-Repeater::make('Cats')->buttonLabel('Add Cat')
+Repeater::make('Cata')->button('Add Cat')

The weekStartsOn method has been renamed to firstDayOfWeek.

-DatePicker::make('Date')->weekStartsOn(1)
+DatePicker::make('Date')->firstDayOfWeek(1) // or use `weekStartsOnMonday` or `weekStartsOnSunday`

The prepend method has been renamed to prefix.

-Number::make('Price')->prepend('$')
+Number::make('Price')->prefix('$')

The append method has been renamed to suffix.

-Number::make('Price')->append('€')
+Number::make('Price')->suffix('€')

The stylisedUi method has been renamed to stylized on the TrueFalse field.

-TrueFalse::make('Disabled')->stylisedUi(onText: 'Yes')
+TrueFalse::make('Disabled')->stylized(on: 'Yes')

The stylisedUi method has been split into two methods stylized and lazyLoad on the Select field.

-Select::make('Friends')->stylisedUi()
+Select::make('Friends')->stylized()

-Select::make('Friends')->stylisedUi(true)
+Select::make('Friends')->lazyLoad()

The fileSize method has been split into two methods minSize and maxSize.

-Image::make('Background')->fileSize('400 KB', 5)
+Image::make('Background')->minSize('400 KB')->maxSize(5)

The height method has been split into two methods minHeight and maxHeight.

-Gallery::make('Carousel')->height(100, 1000)
+Gallery::make('Carousel')->minHeight(100)->maxHeight(1000)

The width method has been split into two methods minWidth and maxWidth.

-Image::make('Product Image')->width(100, 1000)
+Image::make('Product Image')->minWidth(100)->maxWidth(1000)

The insert method has been renamed to prependFiles.

-Gallery::make('Downloads')->insert('prepend')
+Gallery::make('Downloads')->prependFiles()

The min and max methods has been renamed to minFiles and maxFiles on the Gallery field.

-Gallery::make('Files')->min(1)->max(10)
+Gallery::make('Files')->minFiles(1)->maxFiles(10)

The min and max methods has been renamed to minPosts and maxPosts on the Relationship field.

-Relationship::make('Posts')->min(1)->max(10)
+Relationship::make('Posts')->minPosts(1)->maxPosts(10)

The min and max methods has been renamed to minRows and maxRows on the Repeater field.

-Repeater::make('Items')->min(1)->max(10)
+Repeater::make('Items')->minRows(1)->maxRows(10)

The min and max methods has been renamed to minLayouts and maxLayouts on the FlexibleContent field.

-FlexibleContent::make('Blocks')->min(1)->max(10)
+FlexibleContent::make('Blocks')->minLayouts(1)->maxLayouts(10)

The min and max methods has been renamed to minInstances and maxInstances on the Layout field.

-Layout::make('Testimonials')->min(1)->max(10)
+Layout::make('Testimonials')->minInstances(1)->maxInstances(10)

The mimeTypes method has been renamed to acceptedFileTypes.

-File::make('Manual')->mimeTypes(['pdf'])
+File::make('Manual')->acceptedFileTypes(['pdf'])

The enableOpacity method has been renamed to opacity.

-ColorPicker::make('Background')->enableOpacity()
+ColorPicker::make('Background')->opacity()

The delay method has been renamed to lazyLoad.

-WysiwygEditor::make('Biography')->delay()
+WYSIWYGEditor::make('Biography')->lazyLoad()

The mediaUpload method has been renamed to disableMediaUpload.

-WysiwygEditor::make('Narrative')->mediaUpload(false)
+WYSIWYGEditor::make('Narrative')->disableMediaUpload()

The message method has been renamed to body.

-Message::make('Heading')->message('Text')
+Message::make('Heading')->body('Text')

The allowArchives method has been renamed to disableArchives.

-PageLink::make('Link')->allowArchives(false)
+PageLink::make('Link')->disableArchives()

The addTerm, loadTerms and saveTerms methods has been renamed to create, load and save.

-Taxonomy::make('Category')->addTerm()->loadTerms()->saveTerms()
+Taxonomy::make('Category')->create()->load()->save()

The returnFormat method has been renamed to format on all fields.

-Select::make('Superhero')->returnFormat('value')
+Select::make('Superhero')->format('value')

The Instructions trait has been renamed to HelperText.

-use Extended\ACF\Fields\Settings\Instructions;
+use Extended\ACF\Fields\Settings\HelperText;

The MimeTypes trait has been renamed to FileTypes.

-use Extended\ACF\Fields\Settings\MimeTypes;
+use Extended\ACF\Fields\Settings\FileTypes;

The CharacterLimit trait has been renamed to MaxLength.

-use Extended\ACF\Fields\Settings\CharacterLimit;
+use Extended\ACF\Fields\Settings\MaxLength;

The Pending trait has been renamed to Affixable.

-use Extended\ACF\Fields\Settings\Pending;
+use Extended\ACF\Fields\Settings\Affixable;

The Writable trait has been renamed to Immutable.

-use Extended\ACF\Fields\Settings\Writable;
+use Extended\ACF\Fields\Settings\Immutable;

The SubFields trait has been renamed to Fields.

-use Extended\ACF\Fields\Settings\SubFields;
+use Extended\ACF\Fields\Settings\Fields;

The Message and ReturnFormat traits has been removed.

-use Extended\ACF\Fields\Settings\Message;
-use Extended\ACF\Fields\Settings\ReturnFormat;

Changelog: 13.0.0...14.0.0

13

If you're upgrading to version 13, you'll also need to update your imports. The namespace has been changed to Extended\ACF.

-use WordPlate\Acf\Fields\Text;
-use WordPlate\Acf\Fields\Number;
+use Extended\ACF\Fields\Text;
+use Extended\ACF\Fields\Number;

Changelog: 12.0.0...13.0.0

12

The location query method if has been replaced with where. Please update your field groups accordingly.

use Extended\ACF\Location;

-Location::if('post_type', 'post')
+Location::where('post_type', 'post')

Changelog: 11.0.0...12.0.0

11

The field name is now automatically formatted as snake_case instead of kebab-case.

-Text::make('Organization Number') // organization-number
+Text::make('Organization Number') // organization_number

The Radio field has been renamed to RadioButton.

-Radio::make('Color')
+RadioButton::make('Color')

The Wysiwyg field has been renamed to WysiwygEditor.

-Wysiwyg::make('Text')
+WysiwygEditor::make('Text')

Changelog: 10.0.0...11.0.0

extended-acf's People

Contributors

acf-extended avatar bamwempan avatar dependabot-preview[bot] avatar dependabot[bot] avatar drdogbot7 avatar edvwib avatar ernilambar avatar fiskhandlarn avatar grafikart avatar guicapanema avatar ibes avatar jbbouchet avatar josephfusco avatar kaelansmith avatar lhall-amphibee avatar liamb13 avatar lukasleitsch avatar mattkelliher avatar maximvanhove avatar menno-ll avatar n3storm avatar ogorzalka avatar oraimbaud avatar puredazzle avatar rompiot avatar solaldr avatar staffanmowitz avatar szepeviktor avatar vinkla avatar zangab avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

extended-acf's Issues

Feature idea : set(key, value) on Field

A generic option setter

Sometimes, especially with plugins, I need to set some specific key that aren't registered within ACF API. $config is protected and there is no way (or I missed something) to create an arbitrary configuration.

Before doing a PR I want to discuss the idea :

set() proposition

A set() method could serve as a bridge to add new config keys.

FlexibleContent::make(__('Composants', THEME_TEXTDOMAIN), 'flexibles')
                    ->layouts([
                        $this->block('banner-homepage')
                    ])
                   ->set('btn-icon-only', true)
                   ->set('collapse_all_flexible', true)
                   ->set('hide_collapse', true)

append() proposition

An append() method could be used to add multiple keys

FlexibleContent::make(__('Composants', THEME_TEXTDOMAIN), 'flexibles')
                    ->layouts([
                        $this->block('banner-homepage')
                    ])
                   ->append([
                      'btn-icon-only' => true,
                      'collapse_all_flexible' => true,
                      'hide_collapse' => true
                  ])

Taxonomy field save_terms

Hello,

I have to taxonomy fields on a page :

  1. One with the save_terms with true value
  2. The second with the save_terms with false value.

But when i save my page the second terms with the save_terms with the false value attach his terms to the posts, so he shouldn't.

Cheers

Conditional.php generates wrong field name

I wanted to add conditional logic, but failed to do so.

This is my set up:

//
// News / Blog items
//
$fields = [
    acf_image([
        'name' => 'banner',
        'label' => 'Banner',
        'wrapper' => ['width' => '100%'],
    ]),
    acf_radio([
        'name' => 'thumbnail_options',
        'label' => 'Image or video on thumbnail', 
        'wrapper' => ['width' => '100%'],
        'choices' => ['image' => 'Image',  'youtube' => 'Youtube'],
        'default_value' => '',
        'layout' => 'horizontal',
        'return_format' => 'value',
    ]),
    acf_image([
        'name' => 'thumbnail_image', 
        'label' => 'Thumbnail image', 
        'wrapper' => ['width' => '50%'],
        'conditional_logic' => array(
            array(
                array(
                    'name' => 'thumbnail_options',
                    'operator' => '==',
                    'value' => 'image',
                ),
            ),
        ),
    ]),
    acf_url([
        'name' => 'thumbnail_video',
        'label' => 'Thumbnail video',
        'wrapper' => ['width' => '50%'],
        'conditional_logic' => array(
            array(
                array(
                    'name' => 'thumbnail_options',
                    'operator' => '==',
                    'value' => 'youtube',
                ),
            ),
        ),
    ]),
];

$location = [
    [
        acf_location('post_type', 'post')
    ],
];

acf_field_group([
    'title' => 'News settings',
    'key' => 'group_news',
    'fields' => $fields,
    'style' => 'default',
    'location' => $location,
    'position' => 'normal',
    'hide_on_screen' => ['featured_image', 'categories'],
]);

It only works if I disable the logic in Conditional.php and change the config like this:

array(
    'field' => 'field_news_thumbnail_options',
    'operator' => '==',
    'value' => 'image',
),

Relationship field : PostStatus filter is missing

Hi,

First of all, thanks for this awesome wrapper !
I've searched for the Relationship field and it seems to use Trait for filtering by PostType and by Taxonomies.
But in the ACF documentation for this field ( https://www.advancedcustomfields.com/resources/relationship/#settings Filter by Post Status ) It's also possible to filter by post status.
I don't find anything related to this feature in the Relationship class

Am I missing something ?

Thanks

Ordering Registration / Rendering of Groups for Taxonomies

First, I haven't checked this with posts or users, etc. only taxonomies.

I have a class. I have three methods, each for a different register_extended_field_group().

In my bootstrap class, I have 3 actions, something like:

 add_action( 'acf/init', array( $new_ext_acf, 'register_field_group_region_notification_emails' ), 300 );
 add_action( 'acf/init', array( $new_ext_acf, 'register_field_group_region_schedule_pickups' ), 100 );
 add_action( 'acf/init', array( $new_ext_acf, 'register_field_group_region_pickup_limits' ), 200 );

What's wonky is the actions' priorities aren't working. Regardless of those numbers, the 3 different groups are rendered in the same order.

I even tried:

add_action( 'acf/init', array( $new_ext_acf, 'register_field_group_region_all' ), 300 );

and then in that CB method putting the other methods in the order I needed. But that doesn't work either. The rendered order ignores the order in my code.

Maybe it's not a bug? If not, how do I control the order the groups are rendered in?

Strange issues when setting up languages with Polylang

Hello!

I'm finding some strange issues when translating my post contents with Polylang. Templates using Flexible Contents seem to work fine, but there is something wrong with Custom Post Types.

Primary language posts are fine. But secondary languages don't get the correct data.

For example, secondary language post will get an image as an ID string, while the primary language gets the expected array. And for an a group field, the primary would work as expected, while the secondary gets an empty string.

I'm outputting the data in the template for testing, and both posts have the exact same content:

They aren't set as each others translation. I simply set up their language. Hence, I believe they would just hold the same data.

Any ideas or solutions would be very welcome.

Massive thanks for your work!

add line to changelog of V14

Since V14 of extended acf, a lot of changes have been made.
There is a change I've found that has not been documented in the changelog on the releases page of github.
I think the line below should be added to the changelog.

Renamed message method to body.

Could you please add that for the future developers looking to update?
Thanks :D.

Rename ReadOnly to Writable on 11.x tag

Hello,

Thank you for your amazing work so far. We have a lot of websites running with this package. Many of them are running PHP 7.4 and need an update tot PHP 8. To make this possible we would need to have a version working on both PHP 7 and PHP 8.

I propose to create a 11.x branch where we can ship a minor version to support these. I have already a working branch, but I can not create a PR because there is no 11.x branch on this repo.

You can check it out here: MaximVanhove@5c1aff4

[Feature Request]: Export extended-acf fields from ACF dashboard

The ACF PHP API has remained largely the same for the past decade, as @Log1x stated, and all of the related packages can be considered feature complete. However, there are some areas that I would like to improve in the vinkla/extended-acf package in the future:

  • Introducing the ability to set custom keys, which could be beneficial when converting an exported PHP array from the ACF dashboard or when updating from an earlier version of the package (which I have done multiple times).
  • Adding a method for setting the column width of a field, instead of requiring width to be passed to the wrapper method.
  • Supporting the clone field, although I'm not sure this is necessary; I have never needed to use the field since I stopped registering fields from the dashboard.

perhaps add a feature to export to extended-acf from admin?
or
cli command that does the conversion from array to classes

NOT a small feature tho :)

Originally posted by @chrillep in #126 (comment)

Additional Config Settings

Expected Behavior

Out of curiosity I tried the acf-extended plugin (https://www.acf-extended.com/features/fields/flexible-content), especially the flexible-content feature where u can have a modal as a layout-picker instead of a lousy tooltip. However, I have no option to add any custom config key/values to ANY field and this is actually a problem.

Actual Behavior

I am able to add custom config key-values with a function.
I mean, i can re-create my own "flexible-content" and "layout" field and call the $this->config->set('key', 'value'); but, well, kinda ugly.

Steps to Reproduce the Problem

  1. install / enable acf-extended
  2. use UI to create modal picker (need at least 2 layouts)
  3. can't recreate the modal with code only, as custom config keys are necessary for this

Versions

  • WordPlate: 8.5
  • PHP: 7.4

register multiple field in a foreach

Hi,

I'm adding a new plugin when i want to automate acf field creation. I have an array like this :
`

    $acf_fields = [
        __('Information du coach') => [
            [
                'type' => 'Text',
                [
                    'unique_id' => 'coach_name',
                    'title' => __('Nom'),
                    'description' => __('Le nom du coach'),
                    'required' => true
                ]
            ],
            [
                'type' => 'Text',
                [
                    'unique_id' => 'coach_firstname',
                    'title' => __('Prénom'),
                    'description' => __('Le prénom du coach'),
                    'required' => true
                ]
            ],
        ]
    ];

`

And then the creation method like this :
`

    foreach ($acf_fields as $group => $def) {
        register_extended_field_group([
            'title' => $group,
            'fields' => [
                $this->registerNewFields($def),
            ],
            'location' => [
                Location::if('post_type', $location)
            ],
        ]);
    }`

the registerNewFields :

`

    Text::make($def['title'], $def['unique_id'])
        ->instructions($def['description'])
        ->required(true);

`

But this is not working, i get ( ! ) Fatal error: Uncaught Error: Call to a member function setParentKey() on null in D:\web\Yhellow\WordPress\vendor\wordplate\acf\src\FieldGroup.php on line 49

I don't know how to loop in fields and create with your class.

Thanks for your help

OpenStreetMap creating custom fields

Hi, i hope you're well.

I have a question about how to create customs OpenStreetMap fields. I read and applied the doc but I still get an " Uncaught Error : Class "Extended\ACF\Fields\Field" not found "... I've been checking for several hours now, and every class is included as intended and explained on the doc. I guess I'm missing something, but I have no idea what.

This is not my first time creating custom OSM fields, but the previous times it worked perfectly. I've even tried copying and pasting, but it still doesn't work...

Could you maybe give me some help ?

Meta Query for User Roles field

Problem

Unable to query posts by a meta value that's creating using a User Roles field

Expected Result

Should be able to query posts based on the value of a User Roles custom field. Example query:

get_posts([
    'post_type' => $post_type,
    'posts_per_page' => -1,
    'status' => 'publish',
    'meta_query' => [
        [
            'key' => 'roles',
            'value' => ['administrator'],
            'compare' => 'IN'
        ]
    ]
]);

Layout for Radio field missing

Expected Behavior

layout() field is needed in Radio field.

Actual Behavior

For Radio field, layout() is missing.

Steps to Reproduce the Problem

  1. Radio::make('Sample')->layout('horizontal')

Versions

  • WordPlate: 5.4
  • PHP: 7.2

[Feature Request]: Add column wrapper width helper

A feature I often use is setting the column width of fields with the wrapper width. Currently, this is achieved by using the wrapper method available for all fields. It would be convenient if we could specify the column width directly through a method, eliminating the need to pass an array to the wrapper method.

// before
Text::make('Title')->wrapper(['width' => 50]);

// after
Text::make('Title')->column(50);

[Feature Request]: Add markdown support to instructions

In certain instances, it becomes necessary to apply formatting to text within field instructions, such as bold or italic styles. Rather than requiring the use of HTML, a more convenient approach would be to incorporate support for basic Markdown formatting.

// before
Text::make('Title')->instructions('The left part of the <strong>title</strong>.');

// after
Text::make('Title')->instructions('The left part of the **title**.');

Update 5 to 6

Updating from wordplate/acf 5 to 6 breaks te retrieving of data in the front end.

The fields are displayed in the backoffice though. This can be solved be republishing all posts, but this is an impossible job if we have more than 10.000 posts / pages.

checkbox toggle function

checkbox toggle function not available
Fatal error: Uncaught Error: Call to undefined method WordPlate\Acf\Fields\Checkbox::toggle()
Do we have any alternative way ? Please suggest

Improve field creation with choices method by automatically converting values using `sanitize_title`

When I create fields with the choices method, the keys are usually identical to the values.

ButtonGroup::make('Align')
    ->choices([
        'left' => 'Left',
        'center' => 'Center',
    ])
    ->defaultValue('left');

Rather than converting the values into keys manually, we can use sanitize_title to automatically transform them into snake_case, thus obtaining the same outcome.

ButtonGroup::make('Align')
    ->choices(['Left', 'Center'])
    ->defaultValue('left');

We could go even further by allowing the array items to be passed as arguments to a function, making it even cleaner.

ButtonGroup::make('Align')
    ->choices('Left', 'Center')
    ->defaultValue('left');

Documentation: Custom Fields

After discussion in #44 we came up with the idea to add a section to the documentation about creating custom fields by extending the default Field class. This will make it easier to use this package with third-party fields.

Taxonomy example doesn't work

Expected Behavior

When using the following code :

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
    ->addTerms() // Allow new terms to be created whilst editing
    ->loadTerms() // Load value from posts terms
    ->saveTerms() // Connect selected terms to the post
    ->returnFormat('id'); // id or object

You've got the error

Fatal error: Uncaught Error: Call to undefined method WordPlate\Acf\Fields\Taxonomy::addTerms() 

I understand that the method should be replaced by createTerms?

Actual Behavior

Steps to Reproduce the Problem

Copy the example and try it.

Versions

  • WordPlate: 8.5.0

Tab field: Conditional Logic

Expected Behavior

I tried to add a conditional logic to the Tab field as this is possible via ACF but the corresponding trait is not used on the Tab field. I should be able to add a conditional logic to a Tab field with the ->conditionalLogic([...]) function call.

Actual Behavior

The function call results in a Fatal Error: Uncaught Error: Call to undefined method WordPlate\Acf\Fields\Tab::conditionalLogic() ...

Steps to Reproduce the Problem

1. Import Tab field
2. Create Tab field
3. Try adding conditional logic

Versions

  • WordPlate: 8.4.0
  • PHP: 7.4.5

Add ACF number field float support for min and max field properties

I'm attempting to make a number field, however the number field does not support using floats as the min or max option.
It does however support this for the step option.

At this moment, creating a setup like this is therefore impossible:

$field = Number::make( _x( 'Some label', 'Fields', 'some-textdomain' ), 'some-field-name' )
	->min( 0.5 ) // Impossible
	->max( 1.5 ) // Impossible
	->step( 0.1 )
	->defaultValue( 1.0 )
	->required();

`layout()` missing for ButtonGroup field

Expected Behavior

layout() is needed in ButtonGroup field.

Actual Behavior

For ButtonGroup field, layout() is missing.

Steps to Reproduce the Problem

  1. ButtonGroup::make('Sample')->layout('vertical')

Versions

  • WordPlate: 8.3
  • PHP: 7.2

some acf-extended-specific settings (`acfe_*`) have no effect

ACF Extended adds some settings to existing fields (prefixed with acfe_). It seems that they have no effect when added to a field via the withSettings() methods. When configuring this setting in the ACF UI, I can confirm that it has the desired effect.

I saw #105 but it seems like I'm running into something else, as I'm running a current version of extended-acf.

The simplest example I found that doesn't require the premium version of that plugin is the "Instruction Placement" addition of a tooltip option to the instruction_placement field setting:

Text::make('Title')
	->instructions('Write an instruction.')
    ->withSettings([
        'instruction_placement' => 'acfe_instructions_tooltip',
    ])

The issue isn't just localised to instruction_placement. I haven't been able to get the Display Title setting working either (though it's possible I'm misunderstanding its intended usage):

Text::make('Title')
    ->withSettings([
        'acfe_display_title' => 'Not a Title',
    ])

However, the issue doesn't affect all ACFE settings. The "stylised button" setting added to Repeater works for me:

Repeater::make('Items')
    ->instructions('Select up to three.')
    ->withSettings([
        'acfe_display_title' => 'The Items', // doesn't work
        'acfe_repeater_stylised_button' => 1, // works!
        'instruction_placement' => 'acfe_instructions_tooltip', // doesn't work
    ])

Use ACF Extended with Extended ACF (whats in the name?)

Hi,

We love your implementation of ACF. But we are also a big fan of https://www.acf-extended.com. We are just not sure how to activate this programmaticly. We are currently extending the FlexibleContent class to add the settings the plugin uses;

class OurFlexibleContent extends Field
{
    function isExtended()
    {
        $this->settings['acfe_flexible_advanced'] = 1;
		$this->settings['acfe_flexible_stylised_button'] = 1;
		$this->settings['acfe_flexible_layouts_templates'] = 0;
		$this->settings['acfe_flexible_layouts_placeholder'] = 0;
		$this->settings['acfe_flexible_layouts_thumbnails'] = 1;
		$this->settings['acfe_flexible_layouts_settings'] = 0;
		$this->settings['acfe_flexible_layouts_state'] = 'user';
		$this->settings['acfe_flexible_modal_edit'] = array(
			'acfe_flexible_modal_edit_enabled' => '0',
			'acfe_flexible_modal_edit_size' => 'large',
		);

		$this->settings['acfe_flexible_async'] = array(
			0 => 'layout',
		);

		$this->settings['acfe_flexible_add_actions'] = array(
			0 => 'title',
			1 => 'toggle',
			2 => 'copy',
			3 => 'close',
		);

        return $this;
    }
}

Using this extended class works, except that ACF Extended settings are not visible. Is it even a possibility?

[Suggestion] Better way to setup ACF

I found installing ACF using private-composer-installer a safer way to do things.

This allows the key to be stored in the .env file rather than plain text in the composer.json.

Plugin type can also be set to: wordpress-muplugin.

composer.json example:


"require": {
    ...
    "advanced-custom-fields/advanced-custom-fields-pro": "^5.0.0"
},
"repositories": [
    ...
    {
    "type": "package",
        "package": {
            "name": "advanced-custom-fields/advanced-custom-fields-pro",
            "version": "5.7.12",
            "type": "wordpress-plugin",
            "dist": {
               "type": "zip",
                "url": "https://connect.advancedcustomfields.com/index.php?a=download&p=pro&k={%ACF_KEY}&t={%version}"
            },
            "require": {
                "ffraenz/private-composer-installer": "^5.0"
            }
        }
    }
],

Issue with conditional logic in repeaters

Expected Behavior

Hello guys,
You have the possibility, inside a repeater, to apply a condition to a field. This condition can come from another field which is at the same level as the repeater.

Actual Behavior

In fact, the condition inside the repeater not working if the condition come from to level above. My field '--title' or '--texte' are always present.

Steps to Reproduce the Problem

My code :

ButtonGroup::make('Choice ','sh-button')
   ->choices([
	 'text' =>  'Text',
	  'title' => 'Title',
	  'nothing' => 'Nothing',
    ])
    ->defaultValue('title')
    ->returnFormat('value') 
    ->layout('horizontal'),
Repeater::make('Content','sh-repeater')
   ->buttonLabel('add slide')
   ->min(1)
    ->fields([
         Textarea::make('Titre de la section', '--title')
             ->conditionalLogic([
                   ConditionalLogic::if('sh-button')->equals('title')
               ]),
         Textarea::make('Titre de la section', '--texte')
             ->conditionalLogic([
	          ConditionalLogic::if('sh-button')->equals('text'),
              ]),
      ])
      ->conditionalLogic([
	ConditionalLogic::if('sh-button')->notEquals('nothing'),
     ]),

Versions

  • WordPlate: 8.4
  • PHP: 7.4.2

acf_conditional() not working in v5.0.0/v5.1.0

When updating to v5.0.0, I noticed the conditional logic wasn't functioning. It works on version 4.0.0. After comparing the code I noticed that the cause is line 119 of Field.php.

v5.0.0
$conditional = new Conditional($rules, $this->getKey());

-> Not working!

v4.0.0
$conditional = new Conditional($rules, $this->parentKey);

-> Working!

When replacing the line from version 4.0.0, it works as it should!

Below the code when registering the fields

acf_field_group([
    'key' => 'group_test',
    'title' => 'Test',
    'fields' => [
        acf_true_false([
            'label' => 'Toggle',
            'name' => 'column'
        ]),
        acf_text([
            'label' => 'Title',
            'name' => 'column_title',
            'conditional_logic' => [[acf_conditional('column', '1')]]
        ]),
    ],
     'location' => [   
        [acf_location('post_type', 'realisation')],
    ],
]);

"translations" field and arbitrary setting

When translation is enabled on Wordpress the field get a new setting that handle translation

image

I would like to be able to set this setting for my field but there is no way to do it at the moment

A temporary solution would be to extend ACF fields, but since this option is on a lots of field it is a bit problematic. Could we expose a methode addSetting() on Field so we can on the fly add arbitrary setting ?

Bad return on the call of a repeater generate

Predictable behavior

I should have a table with my different fields included in my repeater.

Actual behavior

I get the number of elements to create
when I dump:
dump ($match, get_field ('site', $match-> ID));
I take back
" 1 "

instead of retrieving with the same fields generate in the ACF administration:
0 => [ "url" => [ "title" => "Home" "url" => "// localhost: 3000 /" "target" => "" ] "logo" => [] ]

Steps to reproduce the problem

I can't reproduce the bug

Versions

- WordPlate: ^ 8.4
- PHP: ^ 7.3

Conditional logic with or

Hello here !

Thanks for this beautiful plugin !
I have a question i'm using a conditional logic on a field but the conditional logic could check if the value of the previous field equal one value or one other.

\WordPlate\Acf\Fields\Radio::make('Couleur associée', 'archive_color')
            ->conditionalLogic([
                \WordPlate\Acf\ConditionalLogic::if('archive_type')->equals('cat'),
                WordPlate\Acf\ConditionalLogic::or('archive_type')->equals('dis_sport')
            ])
            ->required()

I tried that but it doesn't work yet.

How to do that ?

Cheers

Remove hack from Layout trait

$key = __CLASS__ === 'WordPlate\Acf\Fields\Layout' ? 'display' : 'layout';

This is a big hack 😿 and not testable.

Please have two different traits instead: Layout and Display.

Snippets

Did you create any editor snippets for the acf helpers yet? I'm whiling to create those for vs code.

Removal of ACF Options page

Hello!

I see here that you removed the options page from the docs but it seems to still be operational in the code. Are there plans to remove it all together? I want to use it, but want to make sure it will still be around soon.

Thanks for the package...love it!

Add `stylisedUi()` for Select field

Expected Behavior

In Select field, ACF allows stylised UI parameter.

Actual Behavior

stylisedUi() is missing for Select

Steps to Reproduce the Problem

Select::make('Selection')
	->defaultValue( 'dark' )
	->stylisedUi(true)
	->choices(
		array(
			'dark'  => 'Dark',
			'white' => 'White',
			'red'   => 'Red',
			'blue'  => 'Blue',
		)
	),

Versions

  • WordPlate: 8.3
  • PHP: 7.2

cannot get wordplate/extended-acf to render Gutenberg blocks

ACF Pro is very proud of the fact that you can jump right in and create Gutenberg blocks using field groups. I set it up in a wordplate project, using extended-acf, and following the ACF Pro blocks guide. I've double- and triple- checked it, but I can't get the blocks to render.

Here's what I have:

theme/functions.php

...
// Action Bar
function init_block_action_bar () {
  if (function_exists('acf_register_block_type')) {
    acf_register_block_type(array(
      'name' => 'action-bar',
      'title' => __('Action Bar'),
      'description' => __('Full width bar layout with title and CTA'),
      'render_template' => 'partials/blocks/action-bar/action-bar.php',
      'category' => 'layout',
      'icon' => 'align-wide',
      'mode' => 'edit',
      'keywords' => array('action bar', 'cta'),
      'post_types' => array('post', 'page'),
    ));
  }
}
add_action('acf/init', 'init_block_action_bar');
...

theme/partials/blocks/action-bar/action-bar.php

<?php
/**
 * Action Bar Block Template
 * @param    array $block The block settings and attributes
 * @param    string $content The block inner HTML (empty)
 * @param    bool $is_preview True druing AJAX preview
 * @param    (int|string) $post_id The post ID this block is saved to
 * 
 * @package  newco
 * @since    newco 0.5
*/

$id = 'action-bar-' . $block['id'];
if (!empty($block['anchor'])) {
  $id = $block['anchor'];
}
$className = 'action-bar';
if (!empty($block['className'])) {
  $className .= ' ' . $block['className'];
}
if (!empty($block['align'])) {
  $className .= ' align' . $block['align']; 
}

$bg_color = get_field('bg_color');
$bg_color_class = ' bgcolor--' . $bg_color;

$padding_classes = '';
if (get_field('add_padding')) {
  $padding = get_field('padding');
  $top_padding_class = $padding['top_padding'] == 0
    ? ''
    : ' spacer__layout--pt-' . $padding['top_padding'];
  $padding_classes .= $top_padding_class;
  $bottom_padding_class = $padding['bottom_padding'] == 0
    ? ''
    : ' spacer__layout--pb-' . $padding['bottom_padding'];
  $padding_classes .= $bottom_padding_class;
}

$title = get_field('title');
$cta = get_field('cta');
$target = $cta['target'] == '_blank'
  ? ' target="' . esc_attr($cta['target']) . '" rel="noreferrer"'
  : '';
?>

<section id="<?=$id;?>">
  <div class="container-fluid<?=$bg_color_class;?><?=$padding_classes;?>">
    <div class="row">
      <div class="col">
        <div class="<?=$className;?>">
          <div>
            <span class="heading-3"><?=$title;?></span>
            <span><a class="button button--secondary spacer__element--ml-48" href="<?=esc_url($cta['url']);?>"<?=$target;?>><?=$cta['title'];?></a></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

In the CMS, I added a Block: Action Bar field group with the corresponding inputs:

image

So far so good. Now if I edit a Page, and add a block, my Action Bar block appears as an option. Beautiful, right? Now I select Action Bar, the ACF fields appear and I can fill them out. So cool! Then I update the edit page and reload the rendered page and...sad trombone...no Gutenberg block. However, in the browser inspector, where the block should appear, the data from the block shows up as commented JSON, like so:

<!-- wp:acf/action-bar {
    "id": "block_600b3c72cad43",
    "name": "acf\/action-bar",
    "data": {
        "bg_color": "yellow",
        "_bg_color": "field_600b286c7031d",
        "add_padding": "1",
        "_add_padding": "field_600b2d06b567a",
        "padding_top_padding": "96",
        "_padding_top_padding": "field_600b2add7031f",
        "padding_bottom_padding": "0",
        "_padding_bottom_padding": "field_600b2db596112",
        "padding": "",
        "_padding": "field_600b2a107031e",
        "title": "Ready to move from idea to impact?",
        "_title": "field_600b2e1f90c6a",
        "cta": {
            "title": "Contact Us",
            "url": "\/",
            "target": ""
        },
        "_cta": "field_600b2ead90c6b"
    },
    "align": "",
    "mode": "edit",
    "className": "aaack"
} /-->

This is where I get stuck. I can't figure out how to get this data to render as the template file. I did a test in a vanilla WordPress ACF Pro instance and the blocks render as expected, easy-peasy. Is there something in wordplate/extended-acf that is preventing this from working? Is it a scoping issue? Not sure where to go from here.

column() must be specified after wrapper()

@vinkla Love the new column() method. I noticed that if you specify column() followed by wrapper(), wrapper() will override column(); example:

Image::make('Logo')
  ->instructions('For use on light backgrounds')
  ->column(50),
Image::make('Logo on dark')
  ->instructions('For use on dark backgrounds')
  ->column(50)
  ->wrapper(['class' => 'dark-bg']),

In this case ^, the second Image field won't be 50%. The simple solution is to move column() after wrapper():

Image::make('Logo')
  ->instructions('For use on light backgrounds')
  ->column(50),
Image::make('Logo on dark')
  ->instructions('For use on dark backgrounds')
  ->wrapper(['class' => 'dark-bg'])
  ->column(50),

and I can confirm that in this case ^, the class of 'dark-bg' still gets applied. So this isn't really a bug, but perhaps you could add a note to the README?

WYSIWYG field : Use custom toolbar

Expected Behavior

Hello everyone,

According to the ACF documentation, you can define a custom toolbar in WYSIWYG field. Currently, you can define toolbar in extended-acf with ->toolbar(string $toolbar) in Wysiwyg class.

If you create a new toolbar with the name Very Simple (as in the ACF cookbook), and you try to pass the same name in Wysiwyg toolbar method, nothing happens, because ACF use snake case version of name to define which element is used.

toolbar-acf

My question is : it is the code's responsibility to turn all names into a snake case version, or the documentation for this project should be more explicit ?

Actual Behavior

->toolbar(string $toolbar) supports only snake case names.

Versions

  • WordPlate: 8.5.0
  • PHP: 7.3

returnFormat on ButtonGroup not working

Expected Behavior

the returnFormat should be a field on ButtonGroup.

Actual Behavior

Causes an error:

Call to undefined method WordPlate\Acf\Fields\ButtonGroup::returnFormat()

Steps to Reproduce the Problem

  1. Create a ButtonGroup
  2. add ->returnFormat('value')

EG:

use WordPlate\Acf\Fields\ButtonGroup;

ButtonGroup::make('My Button', 'my_button')
    ->instructions("I am a button group")
    ->choices([
        0 => 'Show',
        1 => 'Hide'
    ])
    ->wrapper([
       'width' => '33%',
       'class' => '',
       'id' => '',
    ])
    ->returnFormat('value')

Versions

  • WordPlate: 8.1.1
  • PHP: 7.2

Cannot disable the Taxonomy field's add_term option

I can see that this library's Taxonomy::createTerm method is a wrapper for ACF's add_term.
Since this is an additive option, I was expecting new term creation to be disabled while editing if createTerm wasn't used.
Looking at the official ACF docs for registering fields via php, it appears that add_term is true by default.

Expected Behavior

Should Allow terms to be created whilst editing.

Taxonomy::make('My Taxonomy')
  ->taxonomy('my_taxonomy')
  ->createTerms();

Should Not allow terms to be created whilst editing.

Taxonomy::make('My Taxonomy')
  ->taxonomy('my_taxonomy');

Actual Behavior

Allows terms to be created whilst editing.

Taxonomy::make('My Taxonomy')
  ->taxonomy('my_taxonomy')
  ->createTerms();

Allows terms to be created whilst editing.

Taxonomy::make('My Taxonomy')
  ->taxonomy('my_taxonomy');

Versions

  • WordPlate: 5.5.3
  • PHP: 7.4.12

Thank you and terrific job with this package! 🙌🏼

Add `message()` for TrueFalse field

Expected Behavior

In TrueFalse field, ACF allows message parameter which is displayed along the checkbox.

Actual Behavior

message() is missing for TrueFalse

Steps to Reproduce the Problem

  1. TrueFalse::make('Sample TF')->message('Enable this to do something.')

Versions

  • WordPlate: 8.3
  • PHP: 7.2

Failed to display anything using acf_repeater

I tried to user acf_repeater as one of the sub_fields of acf_group, but only labels are showing up, no inputs. :(

acf_field_group( [
	'title'    => 'Overtime',
	'fields'   => [
		acf_group( [
			'label'      => '',
			'name'       => 'preschool',
			'layout'     => 'row',
			'sub_fields' => [
				acf_select( $preschool_id_args ),
				acf_select( $child_list_args ),
				acf_repeater( [
					'label'        => 'Pickup Date & Time',
					'name'         => 'pickup',
					'minimum_rows' => 1,
					'layout'       => 'row',
					'sub_fields'   => [
						acf_date_time_picker( [
							'label' => 'Date & Time',
							'name'  => 'date_time',
						] ),
					],
				] ),
			],
		] ),
	],
	// 'position' => 'acf_after_title',
	'style'    => 'seamless',
	'location' => [
		[
			acf_location( 'post_type', 'overtime' ),
		],
	],
] );

[Feature Request]: Ideas for implementing custom fields

The application I'm working on contains multiple blocks with the field below. Currently, we have kept the code in a WET approach, copying and pasting the block across all blocks.

Extended\ACF\Fields\Text::make('HTML Anchor ID', 'block_id')->helperText(
    'Enter a word or two — without spaces — to make a unique web address just for this block, called an “anchor.” Then, you’ll be able to link directly to this section of your page. [Learn more about anchors.](https://wordpress.org/documentation/article/page-jumps/)',
);

It would be great to create a custom field class and import it instead:

App\Fields\BlockID::make();

The Field class can be extended. However, if you want to overwrite the make method, you must include the arguments for label and name to comply with the Field class.

App\Fields\BlockID::make('HTML Anchor ID', 'block_id');

What can we do instead? We could set up a new method called create that calls the make method internally, but it would be nice to be able to use the make method without passing any arguments. We can keep all settings internal in the BlockID field class. We could also add default values to the make parmeters.

Do you have any ideas on how to improve this? How do Laravel Nova or Filament handle this?

custom taxonomy, change order and order by

hello, I'am trying to change the order and orderby in the loop of a custom taxonomy.

`function topico_pre_get_posts( $query ){

if( !is_admin() && is_tax('topico') && $query->is_main_query() && $query->is_tax() ){


	$order = isset($_POST['order_custom']) ? $_POST['order_custom'] : 'DESC';
    
    $query->set('acfe_single_order', $order); 
	$query->set('acfe_single_orderby', 'title');


    return $query;
}

}
add_action( 'pre_get_posts', 'topico_pre_get_posts' );`

It seems that acfe_single_orderby and acfe_single_order can't be overridden. Or do I miss something!

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.