I'm making a class to add metaboxes to Wordpress extending functionality of Metabox.io.
Now you often have metaboxes with the same attributes (for example for the same post type). I want to group these so you don't have to duplicate those attributes.
I have a function add() which simply adds a metabox.
Now I want the group() method to do the following:
$manager->group([ 'post_types' =>'page', ], function() use ($manager) { $manager->add('metaboxfromgroup', [ 'title' => __( 'Metabox added from group!', 'textdomain' ), 'context' => 'normal', 'fields' => [ [ 'name' => __( 'Here is a field', 'textdomain' ), 'id' => 'fname', 'type' => 'text', ], ] ]); }); So my group() method accepts an array of attributes, which need to be added to the array of attributes of every single add() in the Closure.
Laravel does this really beautifully with Routes, looks something like this:
Route::group(['middleware' => 'auth'], function () { Route::get('/', function () { // Uses Auth Middleware }); Route::get('user/profile', function () { // Uses Auth Middleware }); }); What would be the best way to achieve this?
EDIT:
This is my Metabox manager class
namespace Vendor\Lib; use Vendor\App\Config as Config; final class Metabox { /** @var string */ protected $prefix; /** @var array */ static private $metaboxes = []; public static function getInstance() { static $inst = null; if ($inst === null) { $inst = new Metabox(); } return $inst; } /** * Metabox constructor. * * @param string $prefix */ private function __construct() { $this->prefix = Config::get('metabox.prefix'); } /** * Add a new metabox. * * @param string $id * @param array $attributes */ public function add( $id, array $attributes ) { $attributes['id'] = $id; array_walk_recursive( $attributes, function ( &$value, $key ) { if ( $key === 'id' && substr( $value, 0, strlen( $this->prefix ) ) !== $this->prefix ) { $value = $this->prefix . $value; // auto prefix } } ); self::$metaboxes[] = $attributes; } public function group( $attributes, $function) { // here comes group method } /** * Register the metaboxes. */ public function register() { add_filter( 'rwmb_meta_boxes', function () { return self::$metaboxes; } ); } }