Metabox example
geotonics opened this issue · 2 comments
Can someone please show me an example of how to create a metabox with a custom field using the functions in this template? Are there any plugins which use this template that I can look at? Is there a better place to ask this question?
I will try to explain the problem further.
If I put this code in /WordPress-Plugin-Template|wordpress-plugin-template.php
// This creates a custom post type "listing"
WordPress_Plugin_Template()->register_post_type( 'listing', __( 'Listings', '' ), __( 'Listing', 'wordpress-plugin-template' ) );
// This adds a metabox to "listing" and "page" post types.
add_action( 'add_meta_boxes', 'add_meta_box_1');
function add_meta_box_1(){
WordPress_Plugin_Template()->admin->add_meta_box ('metabox_1',__( 'Metabox 1', 'wordpress-plugin-template' ), array("listing",'page'));
}
When WordPress_Plugin_Template()->admin->add_meta_box is run, it calls this function for each post type.
add_meta_box( $id, $title, array( $this, 'meta_box_content' ), $post_type, $context, $priority, $callback_args );
This in turn calls $this->meta_box_content which gets the fields for the metaboxes like this:
$fields = apply_filters( $post->post_type . '_custom_fields', array(), $post->post_type );
This is what I totally do not understand. How can I add the fields so that this line of code can get the fields for the metabox? Where are these fields supposed to come from?
I was able to make some fields for a metabox using the functions in this plugin.
This code in the $this->meta_box_content() function is looking for a filter named $post->post_type . '_custom_fields'
$fields = apply_filters( $post->post_type . '_custom_fields', array(), $post->post_type );
For a custom post type "listing" the user will have to create a filter called
listing_custom_fields
And that filter needs to have a function added to it to create the custom data entry fields. In this example, I added a function called
add_listing_custom_fields
Here is the all the code in one place, which I put into my copy of wordpress-plugin-template.php
// Create a custom post type
WordPress_Plugin_Template()->register_post_type( 'listing', __( 'Listings', '' ), __( 'Listing', 'wordpress-plugin-template' ) );
// Add a metabox to page and listing post types
add_action( 'add_meta_boxes', 'add_meta_box_1');
function add_meta_box_1(){
WordPress_Plugin_Template()->admin->add_meta_box ('metabox_1',__( 'Metabox 1', 'wordpress-plugin-template' ), array("listing",'page'));
}
// Add custom post fieds to metabox_1
function add_listing_custom_fields(){
$fields=array();
$fields[]=array(
"metabox"=>array(
'name'=>"metabox_1"
),
'id'=>"metabox_1_field_1",
'label'=>"Metabox_1_field_1 Label",
'type'=>'text',
'placeholder'=>"the placeholder",
'description'=>"the description"
);
return $fields;
}
// Add the function to the filter.
add_filter("listing_custom_fields", "add_listing_custom_fields");