-1

I'm writing a plugin to add a set of custom fields to the "edit page" admin screen, using Custom Meta Boxes 2 plugin. That's what I wrote so far:

<?php
/**
 * Plugin Name:     foo Page Banner
 * Plugin URI:      http://www.foo.eu
 * Description:     foo custom widget to display a media element banner with custom text, title and links
 * Text Domain:     foo
 * Domain Path:     /languages
 * Version:         0.0.1
 *
 * @package         foo_Page_Banner
 * @version         0.0.1
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'cmb2_init', 'add_foo_page_cmb2_metaboxes' );
function add_foo_page_cmb2_metaboxes() {

    $prefix = '_foo_page_';

    $cmb = new_cmb2_box( array(
        'id'           => $prefix . 'banner_media',
        'title'        => __( 'Banner media', 'foo' ),
        'object_types' => array( 'page' ),
        'context'      => 'advanced',
        'priority'     => 'default',
    ) );

    $cmb->add_field( array(
        'name' => __( 'Banner Title', 'foo' ),
        'id' => $prefix . 'banner_title',
        'type' => 'text_small',
        'default' => 'page title',
        'desc' => __( 'Banner Title', 'foo' ),
    ) );

    $cmb->add_field( array(
        'name' => __( 'Banner media', 'foo' ),
        'id' => $prefix . 'banner_media',
        'type' => 'file',
    ) );

    $cmb->add_field( array(
        'name' => __( 'Banner Description', 'foo' ),
        'id' => $prefix . 'banner_description',
        'type' => 'text_medium',
        'default' => 'page description',
    ) );

    $cmb->add_field( array(
        'name' => __( 'Banner Links', 'foo' ),
        'id' => $prefix . 'banner_links',
        'type' => 'text_url',
        'default' => 'http://www.example.com',
        'repeatable' => true,
    ) );

}

I sense I need to add specific action to load the add_foo_page_cmb2_metaboxes function only when the current admin screen is a page edit screen. Am I wrong? How do I achieve this?

1

In you code you are passsing 'Page' as object types.

Please update your code as follows:

$cmb = new_cmb2_box( array(
        'id'           => $prefix . 'banner_media',
        'title'        => __( 'Banner media', 'foo' ),
        'object_types' => array( 'post' , 'page' ),
        'context'      => 'advanced',
        'priority'     => 'default',
    ) );

When set object types to Post and Page both then it will be available to both post types. you can also include any custom post type as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.