wpify / custom-fields

GNU General Public License v2.0
6 stars 3 forks source link

WPify Custom Fields

This library provides custom fields for WordPress and WooCommerce via simple API. The custom fields are stored in plain metadata so that you can access them via standard WordPress functionality. The frontend is written in React.js and has no dependencies in PHP. The library also doesn't include React itself but uses react as a dependency from WordPress. Therefore, the library is small and fast but requires at least WordPress 5.3.

Overview

At the moment, you can add custom fields to the following locations:

The custom fields themselves use the standard HTML inputs, so it's recommended to use Google Chrome or Firefox to use the custom fields. This allows having a small footprint and a speedy frontend for the custom fields. You have available wide variety of custom field types:

Some fields also allow multiple values. You can also sort the values via drag&drop.

Advanced usage:

Requirements

Development requirements

If you want to help with the development of the library, feel free to extend that. In addition to the requirements above, you will need also:

Example: Hello custom fields

The following example shows you how to add custom fields to a page and read the data.

  1. Require the library in your plugin via composer: composer require wpify/custom-fields

  2. Include composer autoloader in your plugin: include_once __DIR__ . '/vendor/autoload.php';

  3. Create a new metabox with some text field:

wpify_custom_fields()->create_metabox( array(
   // Metabox title
   'title'      => 'Hello custom fields',
   // Array of post types that will have the custom fields
   'post_types' => array( 'page' ),
   // Array of items for the metabox
   'items'      => array( 
      // Text field
      array(
         'type'  => 'text',
         'title' => 'Text label of the meta',
         'id'    => 'some_id_of_the_meta',
      ),
   ),
) );

That's it :)

Implementations

How to add custom fields to post type?

Adding a metabox to the post

The example above shows the minimalistic example of how to add a metabox. Let's extend that with full list of options. In snippet above, you can see all the options with their default values:

wpify_custom_fields()->create_metabox( array(
   'id'            => null,
   'title'         => null,
   'screen'        => null,
   'context'       => 'advanced',
   'priority'      => 'default',
   'callback_args' => null,
   'items'         => array(),
   'post_types'    => array(),
   'display'       => function() {
      // Conditional display
      return true;
   },
) );

Arguments

Please keep in mind that to have custom fields in the post type. For custom post type, add custom-fields in supports array in register_post_type function, or use add_post_type_support function to add support to some existing post type.

Reading the custom fields

To read the data, you can use simply built-in functions:

$some_custom_field_value = get_post_meta( $post_id, 'some_id_of_the_meta', true );

Links

How to add custom fields to the taxonomy term?

Taxonomy custom fields

The functionality adds the meta box both on add and edit screen of taxonomy term:

wpify_custom_fields()->create_taxonomy_options( array(
   'taxonomy' => null,
   'items'    => array(),
   'display'  => function() {
      // Conditional display
      return true;
   },
) );

Arguments

Reading the custom fields

To read the data, you can use simply built-in functions:

$some_custom_field_value = get_term_meta( $term_id, 'some_id_of_the_meta', true );

Links

How to create an options page with custom fields?

Options page

With this library, you can create options pages with ease on the top or second level. There are used core function add_menu_page or add_submenu_page under the hood.

wpify_custom_fields()->create_options_page( array(
   'type'        => 'normal',
   'parent_slug' => null,
   'page_title'  => '',
   'menu_title'  => '',
   'capability'  => 'manage_options',
   'menu_slug'   => null,
   'icon_url'    => null,
   'position'    => null,
   'items'       => array(),
   'display'     => function() {
      // Conditional display
      return true;
   },
) );

Arguments

Reading the custom fields

$some_custom_field_value = get_option( 'some_id_of_the_option' );

Links

How to add custom fields to WooCommerce settings?

WooCommerce settings

If you want to easily add the settings tab or section to the WooCommerce → Settings, you can easily do that with the following piece of code:

wpify_custom_fields()->create_woocommerce_settings( array(
   'tab'     => array( 'id' => '', 'label' => null ),
   'section' => array( 'id' => '', 'label' => null ),
   'items'   => array(),
   'display' => function() {
      // Conditional display
      return true;
   },
) );

Arguments

Reading the settings fields

The WooCommerce settings is stores as standard options and you can read it as follows:

$some_custom_field_value = get_option( 'some_id_of_the_option' );

Links

How to add custom fields to the product options?

Product options

Product options is a great place where to put the custom fields. You can define it as follows:

wpify_custom_fields()->create_product_options( array(
   'tab'          => array(
      'id'       => 'general',
      'label'    => null,
      'priority' => 100,
      'class'    => array(),
   ),
   'init_priority' => 10,
   'display'       => function() {
      // Conditional display
      return true;
   },
   'items'         => array(),
) );

Arguments

Reading the custom fields

The product options are stored as post meta, so you can read the data the same way as any other post meta:

$some_custom_field_value = get_post_meta( $product_id, 'some_id_of_the_meta', true );

Links

How to add custom fields to WooCommerce order with HPOS enabled?

Order metabox

Use Order metabox to add metaboxes to WooCommerce Orders with HPOS enabled. You can define it as follows

$this->wcf->create_order_metabox(
    array(
        'title'      => 'Details',
        'items' => array(
            array(
                'type'  => 'text',
                'id'    => 'test',
                'title' => 'Test',
            ),
        ),
    )
);

Arguments See create_metabox arguments.

Reading the custom fields

The order meta is stored using the standard WooCommerce CRUD functions, so you can read the data the same way as any other order meta:

$order = wc_get_order( $order_id );
$order->get_meta( 'test' );

Links

How to add custom fields to the product variations?

Product options

You can add custom fields to product variations as well. You can define it as follows:

wpify_custom_fields()->create_product_variation_options( array(
   'after'          => 'pricing',
   'init_priority' => 10,
   'display'       => function() {
      // Conditional display
      return true;
   },
   'items'         => array(),
) );

Arguments

Reading the custom fields

The product options are stored as post meta, so you can read the data the same way as any other post meta:

$some_custom_field_value = get_post_meta( $product_variation_id, 'some_id_of_the_meta', true );

Links

How to add custom fields to the membership plan options?

Membership plan options

WooCommerce Membership plan options works similarly to product options. You can define it as follows:

wpify_custom_fields()->create_membership_plan_options( array(
   'tab'          => array(
      'id'       => 'general',
      'label'    => null,
      'priority' => 100,
      'class'    => array(),
   ),
   'init_priority' => 10,
   'display'       => function() {
      // Conditional display
      return true;
   },
   'items'         => array(),
) );

Arguments

Reading the custom fields

The membership plan options are stored as post meta, so you can read the data the same way as any other post meta:

$some_custom_field_value = get_post_meta( $membership_plan_id, 'some_id_of_the_meta', true );

Links

How to generate Gutenberg block with custom fields?

Gutenberg Block

You can easily generate blocks that will use the custom fields interface. if you want to replace default custom fields interface with your own, simply set the editor_script and editor_style attributes with handle of your registered script and style. Every registered block also have wcf attribute, that contains the definition of the custom fields used in the block.

wpify_custom_fields()->create_gutenberg_block( array(
    'name'             => null, // string
    'title'            => null, // string
    'category'         => 'common', // string
    'parent'           => null, // string
    'icon'             => null, // string
    'description'      => null, // string
    'keywords'         => array(), // array
    'textdomain'       => null, // string
    'styles'           => array(), // array
    'supports'         => null, // array
    'example'          => null, // array
    'render_callback'  => null, // callable
    'attributes'       => array(), // array
    'uses_context'     => array(), // array
    'provides_context' => null, // array
    'editor_script'    => null, // string
    'script'           => null, // string
    'editor_style'     => null, // string
    'style'            => null, // string
    'items'            => array(), // array
    'display'          => function() {
      // Conditional display
      return true;
   },
) );

Arguments

Move attributes to sidebar

If you want to move the particular attribute of the block to the sidebar, add an option to item 'position' => 'inspector'.

Links

Example

wpify_custom_fields()->create_gutenberg_block( array(
    'name'        => 'wcf/test',
    'title'       => 'Test block',
    'items'       => array(
        array(
            'type'        => 'text',
            'title'       => 'Example text',
            'id'          => 'some_example_text',
            'description' => 'and example description',
            'label'       => 'with example label',
        ),
        array(
            'type'        => 'text',
            'title'       => 'Example text 2',
            'id'          => 'some_example_text_2',
            'description' => 'and example description',
            'label'       => 'with example label',
            'position'    => 'inspector',
        ),
    ),
    'render_callback' => function ( $attributes ) {
        return '<h2>' . $attributes['some_example_text'] . '</h2><p>' . $attributes['some_example_text'] . '</p>';
    },
) );

How to add custom fields to the user?

The functionality adds options to the user:

wpify_custom_fields()->create_user_options( array(
   'items'    => array(),
) );

Arguments

Reading the custom fields

To read the data, you can use simply built-in functions:

$some_custom_field_value = get_user_meta( $user_id, 'some_id_of_the_meta', true );

Links

How to add custom fields to comments?

Adding a metabox to the post

You can also easily add custom fields to comments:

wpify_custom_fields()->create_comment_metabox( array(
   'id'    => 'cool_comments_metabox',
    'title' => __( 'Example metabox', '' ),
    'items' => array(
        array(
            'type'  => 'text',
            'id'    => 'test',
            'label' => 'Test metafield'
        ),
    ),
) );

Arguments

See post metabox for available arguments.

Reading the custom fields

To read the data, you can use simply built-in functions:

$some_custom_field_value = get_comment_meta( $post_id, 'some_id_of_the_meta', true );

Links

Custom fields definition

In examples above, only one custom field were shown. But you can define more than just text fields. There are many field types to use. All the fields has some the following attributes in common:

$some_item = array(
   'type'              => '',
   'id'                => '',
   'title'             => '',
   'placeholder'       => '',
   'suffix'            => '',
   'custom_attributes' => array(),
   'description'       => '',
   'display'           => function ( $item, $context ) {
        return true;
   },
);

// Some dummy usage, use `add_*` methods listed above.
wpify_custom_fields()->add_some_custom_field_implementation( array(
   // some options
   'items'    => array( $some_item ),
) );

Common attributes

Attachment field type attachment, multi_attachment

Attachment field type

Additional attributes

Checkbox field type checkbox

Checkbox field type

Additional attributes

Code editor field type code

Code field type

Additional attributes

Color field type color

Color field type

Date field type date

Date field type

Date and time field type datetime

Date and time field type

E-mail field type email

E-mail field type

Group field type group, multi_group

Singular groups group

Group field doesn't have any visual representation, but groups fields into one field. Here is an example of defining the group field in options page:

wpify_custom_fields()->create_options_page( array(
   'id'          => 'example_options_page',
   'page_title'  => 'Hello custom fields',
   'menu_title'  => 'Hello WCF',
   'menu_slug'   => 'hello-wcf',
   'position'    => 1000,
   'items'       => array(
      array(
         'id'              => 'some_example_group',
         'type'            => 'group',
         'title'           => 'Group',
         'items'           => array(
            array(
               'type'            => 'text',
               'title'           => 'Text in group 1',
               'id'              => 'some_example_text_1',
            ),
            array(
               'type'            => 'text',
               'title'           => 'Text in group 2',
               'id'              => 'some_example_text_2',
            ),
         )
      ),
   ),
) );

The result is following:

Group field;

We can now set some values and access the data:

$value = get_option('some_example_group');

The code above will generate following array:

array(
  "some_example_text_1" => "Some value 1",
  "some_example_text_2" => "Some value 2",
);

The groups can also be nested to get much more complicated data structures than in the example above.

Repeated groups multi_group

If we change the field type in example above to multi_group, we'll get a different result:

wpify_custom_fields()->create_options_page( array(
   'id'          => 'example_options_page',
   'page_title'  => 'Hello custom fields',
   'menu_title'  => 'Hello WCF',
   'menu_slug'   => 'hello-wcf',
   'position'    => 1000,
   'items'       => array(
      array(
         'id'              => 'some_example_group',
         'type'            => 'multi_group',
         'title'           => 'Multi group',
         'items'           => array(
            array(
               'type'            => 'text',
               'title'           => 'Text in group 1',
               'id'              => 'some_example_text_1',
            ),
            array(
               'type'            => 'text',
               'title'           => 'Text in group 2',
               'id'              => 'some_example_text_2',
            ),
         )
      ),
   ),
) );

Multi group field

The value in the custom field will be as follows:

array(
    array(
        "some_example_text_1" => "Some text 1",
        "some_example_text_2" => "Some value 2",   
    ),
    array(
        "some_example_text_1" => "Some text 2",
        "some_example_text_2" => "",   
    ),
);

As you can see, you can add a new group with any fields inside it, move the group by drag&drop, and delete group items.

Additional attributes

HTML field type html

HTML Field

Additional attributes

Inner Blocks field type inner_blocks

Inner Blocks are limited in usage, please follow:

Additional attributes

Link field type link

Field that returns an array array( 'url' => '', 'label' => '', 'target' => null, 'post' => null )

Additional attributes

Mapy.cz field type mapycz

Shows the search box for location and map, where the user can set some location. The output is an object with the following shape:

{
  "address": "Praha",
  "latitude": 50.0835493857,
  "longitude": 14.4341412988,
  "zoom": 12
}

Month field type month

Month field

Number field type number

Number field

Password field type password

Password field

Post field type post, multi_post

Post field Post field

Allows selecting posts from a particular post type.

Additional attributes

Select field type select, multi_select

Select field

The select field can accept options asynchronously from API (recommended) or inline from option attribute. Each option must be an associative array with label and value keys.

Additional attributes

Example

$field = array(
    'id'      => 'some_id_of_field',
    'type'    => 'select',
    'label'   => __( 'Example select', 'your_plugin' ),
    'options' => array(
        3 => 'Test 3',
        2 => 'Test 2',
        1 => 'Test 1',
        0 => 'Test 0',
    ),
);

// OR

$field = array(
    'id'      => 'some_id_of_field',
    'type'    => 'select',
    'label'   => __( 'Example select', 'your_plugin' ),
    'options' => array(
        array( 'value' => 3, 'label' => 'Test 3' ),
        array( 'value' => 2, 'label' => 'Test 2' ),
        array( 'value' => 1, 'label' => 'Test 1' ),
        array( 'value' => 0, 'label' => 'Test 0' ),
    ),
);

// OR

$field = array(
    'id'      => 'some_id_of_field',
    'type'    => 'select',
    'label'   => __( 'Example select', 'your_plugin' ),
    'options' => 'callback_that_returns_options_in_shape_as_above',
);

Phone number field type tel

Tel field

Additional attributes

Textarea field type textarea

Textarea field

Text field type text

Text field

Time field type time

Time field

Title field type title

Title field

Toggle field type toggle

Toggle field

Additional attributes

URL field type url

URL field

Week field type week

Week field

WYSIWYG fields type wysiwyg

This field gives you the TinyMCE editor, that enables you edit the HTML visualy!

WYSIWYG field

Additional attributes

Extending the field types

You can extend the custom field types with your own:

  1. Create a React component with the field:
import React, { useState } from 'react';

const MyCustomField = (props) => {
   const { id, className, group_level = 0, value } = props;
   const [currentValue, setCurrentValue] = useState(value);

   return (
     <React.Fragment>
      {group_level === 0 && ( // We need to have the input with the name only if not in group
        <input type="hidden" name={id} value={currentValue}/>
      )} 
      <input
         id={id}
         type="text"
         className={classnames('regular-text', className)}
         onChange={(e) => setCurrentValue(e.target.value)}
         value={currentValue}
      />
     </React.Fragment>
   );
};

export default MyCustomField;
  1. Register the field:
import { addFilter } from '@wordpress/hooks';
import { MyCustomField } from './fields/MyCustomField.js';
const type = 'my_custom_field';
addFilter('wcf_field_' + type, 'my-plugin-slug', Component => MyCustomField);
  1. Register the parser and sanitizer (if needed)

See the code in src/Parser.php and src/Sanitizer.php for filters.

Bedrock support

If you use Bedrock, the custom fields by default won't work, because the vendor folder is outside of the docroot and assets needed for WCF are in the vendor folder. The solution to this is move the WCF to the document root. To enable that, require "mnsami/composer-custom-directory-installer" that enables installation particular packages to another location:

composer require mnsami/composer-custom-directory-installer

After that, you can specify location in your composer.json

{
  ...
  "extra": {
    "installer-paths": {
      ... 
      "web/app/vendor/{$vendor}/{$name}": [
        "wpify/custom-fields"
      ]
    },
    ...
  }
  ...
}

Run composer update and WCF is installed in web/app/vendor/wpify/custom-fields folder. You can then inicialize WCF as follows:

$custom_fields = new CustomFields( content_url( '/app/vendor/wpify/custom-fields' ) );

Advanced usage - conditional custom fields

You can customize custom fields based on data. Let's say when the user selects the white colour, you want to show background color field. That's possible thanks to filters on frontend, you can define the following in your javascript:

import { addFilter } from '@wordpress/hooks';

addFilter('wcf_definition', 'my-plugin-test', (wcf, data) => {
  // Define when to apply filters wery carefully, if you don't want to mess with bugs!
  if (wcf.object_type === 'options_page' && wcf.menu_slug === 'some-test-menu-slug') {
        // Remove the an conditional field if present.
        const newItems = wcf.items.filter(i => i.id !== 'some_background_color');

        // If some_color is white, insert the conditional field after field ID "some_color".
        if (data.some_color === '#ffffff') {
            // Find an index of "some_color" field.
            const index = newItems.map(i => i.id).indexOf('some_color');

            // Insert new field after "some_color" field.
            newItems.splice(index + 1, 0, {
                id: 'some_background_color',
                title: 'Background color',
                type: 'color',
                value: data.some_background_color || '',
            });
        }

        // Return new WCF definition.
        return {
            ...wcf,
            items: newItems,
        };
  }

  // By default, return the original WCF definition.
  return wcf;
});

This approach has some caveats:

You can also use the filter wcf_field_props, that allows you modify e.g. classnames of the field.

import { addFilter } from '@wordpress/hooks';

addFilter('wcf_field_props', 'my-plugin-test', (props) => {
  if (props.appContext.object_type === 'options_page' && props.appContext.menu_slug === 'some-test-menu-slug' && props.id === 'test_field') {
        props.className += ' test-class';
  }

  return props;
});

The code above will add test-class to the field with ID test_field in options page with slug some-test-menu-slug.

Advanced usage - custom getters and setters

If you want to retrieve or save the field value from/to a non-default location, you can easily override the getter and setter with callback_get and callback_set arguments.

Arguments

The following example demonstrates saving and retrieving post meta field with get_option and update_option functions.

wpify_custom_fields()->create_metabox( array(
    'title'      => 'Details',
    'post_types' => array( 'post' ),
    'priority' => 'high',
    'items'      => array(
        array(
            'type'  => 'text',
            'title' => 'Some field',
            'id'    => 'some_field',
            'callback_get' => function($item, $id) {
                // Retrieve the value from wp_options. 
                return get_option($item['id'],'');
            },
            'callback_set' => function($item, $id, $value) {
                // Save the value to wp_options.
                update_option($item['id'],$value);
            },
            ),
        ),
    ) 
);