miya/custom-field

2.3.0 2017-09-27 12:22 UTC

This package is not auto-updated.

Last update: 2024-12-22 04:27:27 UTC


README

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

An abstract class to create a custom field for WordPress.

Install

$ composer require miya/custom-field

Example

<?php

require_once dirname( __FILE__ ) . '/vendor/autoload.php';

$text_field = new Text_Field( 'text', 'Text' );
$text_field->add( 'post' );


class Text_Field extends \Miya\WP\Custom_Field
{
	/**
	 * Fires at the `admin_enqueue_scripts` hook.
	 *
	 * @param string $hook The hook like `post.php` or so.
	 * @return none
	 */
	public function admin_enqueue_scripts( $hook )
	{
		// If you need a CCS or JS, you can run `wp_enqueue_*()` here.
		// This function will be callded when current screen is the specific post type by `add()`.
	}

	/**
	 * Displays the form for the metabox. The nonce will be added automatically.
	 *
	 * @param object $post The object of the post.
	 * @param array $args The argumets passed from `add_meta_box()`.
	 * @return none
	 */
	public function form( $post, $args )
	{
		?>
			<input type="text" name="input"
					value="<?php echo esc_attr( get_post_meta( get_the_ID(), '_input', true ) ); ?>">
		<?php
	}

	/**
	 * Save the metadata from the `form()`. The nonce will be verified automatically.
	 *
	 * @param int $post_id The ID of the post.
	 * @return none
	 */
	public function save( $post_id )
	{
		update_post_meta( $post_id, '_input', $_POST['input'] );
	}
}

The result is following.