Admin Notice

function dk_admin_notice() {
    ?>
    <div class="notice notice-success is-dismissible">
        <p><?php _e( 'This is a success notice.', 'dukeyin' ); ?></p>
    </div>
    <?php
}
add_action( 'admin_notices', 'dk_admin_notice' );

//notice-success //notice-danger //notice-warning //notice-info

Enqueue Style and JavaScripts

Styles

// Enqueue own styles
function dk_enqueue_custom_styles() {
    wp_enqueue_style( 'main',get_template_directory_uri() .'/assets/css/main.css', array(),'1.0','all');

} add_action( ‘wp_enqueue_scripts’, ‘dk_enqueue_custom_styles’ ); //in frontend

add_action( ‘admin_enqueue_scripts’, ‘dk_enqueue_custom_styles’ ); //in admin

add_action( ’login_enqueue_scripts’, ‘dk_enqueue_custom_styles’ ); //in login screen

add_action( ’enqueue_embed_scripts’, ‘dk_enqueue_custom_styles’ ); //embed

Scripts

// Enqueue  scripts frontend
function dk_enqueue_custom_scripts() {
    wp_enqueue_script( 'main', get_template_directory_uri() .'/assets/js/scripts.js', array('jQuery'),'1.0',true);

} add_action( ‘wp_enqueue_scripts’, ‘dk_enqueue_custom_scripts’ ); //in frontend

add_action( ‘admin_enqueue_scripts’, ‘dk_enqueue_custom_scripts’ ); //in admin

add_action( ’login_enqueue_scripts’, ‘dk_enqueue_custom_scripts’ ); //in login screen

add_action( ’enqueue_embed_scripts’, ‘dk_enqueue_custom_scripts’ ); //embed

//“true” = in footer; “false” = in header.

Register Image Size

// Register new image sizes
    add_image_size( 'thiny', 50, 50, array( 'center', 'center' ));
// Make image size selectable
add_filter( 'image_size_names_choose', 'my_custom_sizes' );

function my_custom_sizes( $sizes ) {
    return array_merge( $sizes, array(
        'thiny' =&gt; __( 'Tiney' ),
    ) );
}</code></pre>

Custom User Profile fields

// Add Custom User Profile Fields
// Get user meta on frontend with: get_user_meta( $user_id, "field_id", true );
function dk_user_fields( $user ) {
    $output = '';   $output .= '<h2>'.__("Custom headline", "dukeyin").'</h2>';
        $output .= '<table class="form-table">';
            $output .= '<tr>';
                $output .= '<th><label for="textfiled">'.__("A text Field", "dukeyin").'</label></th>';
                $output .= '<td>';
                    $output .= '<input placeholder="Text Place holder" type="text" name="textfiled" id="textfiled" value="'.esc_attr( get_user_meta( $user->ID, 'textfiled', true ) ).'" class="regular-text" /><br />';
                    $output .= '<span class="description">'.__("Description This is a example of text field", "textfiled").'</span>';                    
                $output .= '</td>';
            $output .= '</tr>';
            $output .= '<tr>';
                $output .= '<th><label for="emailfield">'.__("Email field", "dukeyin").'</label></th>';
                $output .= '<td>';
                    $output .= '<input placeholder="Email Place holder" type="email" name="emailfield" id="emailfield" value="'.esc_attr( get_user_meta( $user->ID, 'emailfield', true ) ).'" class="regular-text" /><br />';
                    $output .= '<span class="description">'.__("Description This is a example of email field", "emailfield").'</span>';                    
                $output .= '</td>';
            $output .= '</tr>';
            $output .= '<tr>';
                $output .= '<th><label for="urlfield">'.__("URLfield", "dukeyin").'</label></th>';
                $output .= '<td>';
                    $output .= '<input placeholder="url placeholder" type="url" name="urlfield" id="urlfield" value="'.esc_attr( get_user_meta( $user->ID, 'urlfield', true ) ).'" class="regular-text" /><br />';
                    $output .= '<span class="description">'.__("Description This is a example of url field", "urlfield").'</span>';                    
                $output .= '</td>';
            $output .= '</tr>';
            $output .= '<tr>';
                $output .= '<th><label for="passwordfield">'.__("Password", "dukeyin").'</label></th>';
                $output .= '<td>';
                    $output .= '<input placeholder="Password placeholder" type="password" name="passwordfield" id="passwordfield" value="'.esc_attr( get_user_meta( $user->ID, 'passwordfield', true ) ).'" class="regular-text" /><br />';
                    $output .= '<span class="description">'.__("Description This is a example of password field", "passwordfield").'</span>';                    
                $output .= '</td>';
            $output .= '</tr>';
            $output .= '<tr>';
                $output .= '<th><label for="numberfield">'.__("Number", "dukeyin").'</label></th>';
                $output .= '<td>';
                    $output .= '<input placeholder="Number placeholder" type="number" name="numberfield" id="numberfield" value="'.esc_attr( get_user_meta( $user->ID, 'numberfield', true ) ).'" class="regular-text" /><br />';
                    $output .= '<span class="description">'.__("Description This is a example of number field", "numberfield").'</span>';                    
                $output .= '</td>';
            $output .= '</tr>';
            $output .= '<tr>';
                $output .= '<th><label for="telfield">'.__("Telephone", "dukeyin").'</label></th>';
                $output .= '<td>';
                    $output .= '<input placeholder="Telephone placehoder" type="tel" name="telfield" id="telfield" value="'.esc_attr( get_user_meta( $user->ID, 'telfield', true ) ).'" class="regular-text" /><br />';
                    $output .= '<span class="description">'.__("Description This is a example of telephone field", "telfield").'</span>';                    
                $output .= '</td>';
            $output .= '</tr>';
            $output .= '<tr>';
                $output .= '<th><label for="datefield">'.__("Date", "dukeyin").'</label></th>';
                $output .= '<td>';
                    $output .= '<input  type="date" name="datefield" id="datefield" value="'.esc_attr( get_user_meta( $user->ID, 'datefield', true ) ).'" class="regular-text" /><br />';
                    $output .= '<span class="description">'.__("Description This is a example of date field", "datefield").'</span>';                    
                $output .= '</td>';
            $output .= '</tr>';  
    $output .= '</table>';
    echo $output;
}

add_action( ‘show_user_profile’, ‘dk_user_fields’ ); add_action( ’edit_user_profile’, ‘dk_user_fields’ );

// Save Custom User Profile Fields function custom_user_fields_save( $user_id ) {

if ( !current_user_can( 'edit_user', $user_id ) ) {
    return false;
    }
    update_user_meta( $user_id, 'textfiled', $_POST['textfiled'] );
    update_user_meta( $user_id, 'emailfield', $_POST['emailfield'] );
    update_user_meta( $user_id, 'urlfield', $_POST['urlfield'] );
    update_user_meta( $user_id, 'passwordfield', $_POST['passwordfield'] );
    update_user_meta( $user_id, 'numberfield', $_POST['numberfield'] );
    update_user_meta( $user_id, 'telfield', $_POST['telfield'] );
    update_user_meta( $user_id, 'datefield', $_POST['datefield'] );

} add_action( ‘personal_options_update’, ‘custom_user_fields_save’ ); add_action( ’edit_user_profile_update’, ‘custom_user_fields_save’ );

WP Mail Function Send a email

// Custom WP Mail Function
$to = '[email protected]';
$subject = 'Welcom to my site';
$headers[] = 'Content-Type: text/html; charset=UTF-8';
$headers[] = 'From: DukeYin <[email protected]>';
$message = 'Your message';

wp_mail( $to, $subject, $message);

Register Nav Menu

function dk_register_nav_menus() {
$locations = array(
       'primary-menu' =&gt; __( 'Primary Menu', 'dukeyin' ),
       'secondary-menu' =&gt; __( 'Secondary Menu', 'dukeyin' ),

);
register_nav_menus( $locations );

} add_action( ‘init’, ‘dk_register_nav_menus’ );

Shortcode

// Create Shortcode star
// Shortcode: [star time="3600" color="fff"]
function create_star_shortcode($atts) {
// Attributes
$atts = shortcode_atts(
    array(
        'time' =&gt; '3600',
        'color' =&gt; 'fff',
    ),
    $atts,
    'star'
);
// Attributes in var
$time = $atts['time'];
$color = $atts['color'];

// Your Code } add_shortcode( ‘star’, ‘create_star_shortcode’ );

Register sidebar

// Register custom sidebars
function dk_custom_sidebars() {
$args = array(
    'name'          =&gt; __( 'Left Side bar', 'dukeyin' ),
    'description'   =&gt; __( 'The left sidebar', 'dukeyin' ),
    'id'            =&gt; 'leftsidebar',
    'class'         =&gt; 'leftside',
    'before_widget' =&gt; '&lt;li id="%1$s" class="widget %2$s"&gt;',
    'after_widget'  =&gt; '&lt;/li&gt;',
    'before_title'  =&gt; '&lt;h2 class="widgettitle"&gt;',
    'after_title'   =&gt; '&lt;/h2&gt;',
);
register_sidebar($args);

$args = array(
    'name'          =&gt; __( 'Right Side bar', 'dukeyin' ),
    'description'   =&gt; __( 'The right sidebar', 'dukeyin' ),
    'id'            =&gt; 'rightsidebar',
    'class'         =&gt; 'rightside',
    'before_widget' =&gt; '&lt;li id="%1$s" class="widget %2$s"&gt;',
    'after_widget'  =&gt; '&lt;/li&gt;',
    'before_title'  =&gt; '&lt;h2 class="widgettitle"&gt;',
    'after_title'   =&gt; '&lt;/h2&gt;',
);
register_sidebar($args);

} add_action( ‘widgets_init’, ‘dk_custom_sidebars’ );

Custom Meta Box

// Meta Box Class: PostExtraFieldMetaBox
// Get the field value: $metavalue = get_post_meta( $post_id, $field_id, true );
class PostExtraFieldMetaBox{
private $screen = array(
    'post',
            'page',
            'custom-post-types',        
);

private $meta_fields = array(
            array(
                'label' =&gt; 'Text',
                'id' =&gt; 'textfield',
                'default' =&gt; 'Default text',
                'type' =&gt; 'text',
            ),

            array(
                'label' =&gt; 'Text Area',
                'id' =&gt; 'textarea',
                'default' =&gt; 'Defaule texts',
                'type' =&gt; 'textarea',
            ),

            array(
                'label' =&gt; 'WYSIWYG',
                'id' =&gt; 'rich-text',
                'default' =&gt; 'Deafult text',
                'type' =&gt; 'wysiwyg',
            ),

            array(
                'label' =&gt; 'Check box',
                'id' =&gt; 'checkbox',
                'default' =&gt; 'true',
                'type' =&gt; 'checkbox',
            ),

            array(
                'label' =&gt; 'Radio',
                'id' =&gt; 'radio',
                'default' =&gt; 'second',
                'type' =&gt; 'radio',
                'options' =&gt; array(
                    'first',
                    'second',
                    'third'
                )
            ),

            array(
                'label' =&gt; 'Select',
                'id' =&gt; 'select',
                'default' =&gt; 'second',
                'type' =&gt; 'select',
                'options' =&gt; array(
                    'first',
                    'second',
                    'third'
                )
            ),

            array(
                'label' =&gt; 'Media',
                'id' =&gt; 'media',
                'type' =&gt; 'media',
                'returnvalue' =&gt; 'url'
            ),

            array(
                'label' =&gt; 'Categories',
                'id' =&gt; 'cat',
                'type' =&gt; 'categories',
            ),

            array(
                'label' =&gt; 'User',
                'id' =&gt; 'user',
                'type' =&gt; 'users',
            ),

            array(
                'label' =&gt; 'Email',
                'id' =&gt; 'email',
                'default' =&gt; '[email protected]',
                'type' =&gt; 'email',
            ),

            array(
                'label' =&gt; 'URL',
                'id' =&gt; 'url',
                'default' =&gt; 'https://www.google.com',
                'type' =&gt; 'url',
            ),

            array(
                'label' =&gt; 'Password',
                'id' =&gt; 'pswd',
                'type' =&gt; 'password',
            ),

            array(
                'label' =&gt; 'Number',
                'id' =&gt; 'number',
                'default' =&gt; '123',
                'type' =&gt; 'number',
            ),

            array(
                'label' =&gt; 'Color',
                'id' =&gt; 'color',
                'default' =&gt; '#eeeeee',
                'type' =&gt; 'color',
            ),

            array(
                'label' =&gt; 'Tel',
                'id' =&gt; 'tel',
                'type' =&gt; 'tel',
            )

);

public function __construct() {
    add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
            add_action( 'admin_footer', array( $this, 'media_fields' ) );
    add_action( 'save_post', array( $this, 'save_fields' ) );
}

public function add_meta_boxes() {
    foreach ( $this-&gt;screen as $single_screen ) {
        add_meta_box(
            'PostExtraField',
            __( 'PostExtraField', 'textdomain' ),
            array( $this, 'meta_box_callback' ),
            $single_screen,
            'advanced',
            'high'
        );
    }
}

public function meta_box_callback( $post ) {
    wp_nonce_field( 'PostExtraField_data', 'PostExtraField_nonce' );
            echo 'The extra data for this post';
    $this-&gt;field_generator( $post );
}
    public function media_fields() {
        ?&gt;&lt;script&gt;
            jQuery(document).ready(function($){
                if ( typeof wp.media !== 'undefined' ) {
                    var _custom_media = true,
                    _orig_send_attachment = wp.media.editor.send.attachment;
                    $('.new-media').click(function(e) {
                        var send_attachment_bkp = wp.media.editor.send.attachment;
                        var button = $(this);
                        var id = button.attr('id').replace('_button', '');
                        _custom_media = true;
                            wp.media.editor.send.attachment = function(props, attachment){
                            if ( _custom_media ) {
                                if ($('input#' + id).data('return') == 'url') {
                                    $('input#' + id).val(attachment.url);
                                } else {
                                    $('input#' + id).val(attachment.id);
                                }
                                $('div#preview'+id).css('background-image', 'url('+attachment.url+')');
                            } else {
                                return _orig_send_attachment.apply( this, [props, attachment] );
                            };
                        }
                        wp.media.editor.open(button);
                        return false;
                    });
                    $('.add_media').on('click', function(){
                        _custom_media = false;
                    });
                    $('.remove-media').on('click', function(){
                        var parent = $(this).parents('td');
                        parent.find('input[type="text"]').val('');
                        parent.find('div').css('background-image', 'url()');
                    });
                }
            });
        &lt;/script&gt;&lt;?php
    }

public function field_generator( $post ) {
    $output = '';
    foreach ( $this-&gt;meta_fields as $meta_field ) {
        $label = '&lt;label for="' . $meta_field['id'] . '"&gt;' . $meta_field['label'] . '&lt;/label&gt;';
        $meta_value = get_post_meta( $post-&gt;ID, $meta_field['id'], true );
        if ( empty( $meta_value ) ) {
            if ( isset( $meta_field['default'] ) ) {
                $meta_value = $meta_field['default'];
            }
        }
        switch ( $meta_field['type'] ) {
                            case 'users':
                                $usersargs = array(
                                    'selected' =&gt; $meta_value,
                                    'echo' =&gt; 0,
                                    'name' =&gt; $meta_field['id'],
                                    'id' =&gt; $meta_field['id'],
                                    'show_option_none' =&gt; 'Select a user',
                                );
                                $input = wp_dropdown_users($usersargs);
                                break;

                            case 'categories':
                                $categoriesargs = array(
                                    'selected' =&gt; $meta_value,
                                    'hide_empty' =&gt; 0,
                                    'echo' =&gt; 0,
                                    'name' =&gt; $meta_field['id'],
                                    'id' =&gt; $meta_field['id'],
                                    'show_option_none' =&gt; 'Select a category',
                                );
                                $input = wp_dropdown_categories($categoriesargs);
                                break;

                            case 'media':
                                $meta_url = '';
                                    if ($meta_value) {
                                        if ($meta_field['returnvalue'] == 'url') {
                                            $meta_url = $meta_value;
                                        } else {
                                            $meta_url = wp_get_attachment_url($meta_value);
                                        }
                                    }
                                $input = sprintf(
                                    '&lt;input style="display:none;" id="%s" name="%s" type="text" value="%s"  data-return="%s"&gt;&lt;div id="preview%s" style="margin-right:10px;border:1px solid #e2e4e7;background-color:#fafafa;display:inline-block;width: 100px;height:100px;background-image:url(%s);background-size:cover;background-repeat:no-repeat;background-position:center;"&gt;&lt;/div&gt;&lt;input style="width: 19%%;margin-right:5px;" class="button new-media" id="%s_button" name="%s_button" type="button" value="Select" /&gt;&lt;input style="width: 19%%;" class="button remove-media" id="%s_buttonremove" name="%s_buttonremove" type="button" value="Clear" /&gt;',
                                    $meta_field['id'],
                                    $meta_field['id'],
                                    $meta_value,
                                    $meta_field['returnvalue'],
                                    $meta_field['id'],
                                    $meta_url,
                                    $meta_field['id'],
                                    $meta_field['id'],
                                    $meta_field['id'],
                                    $meta_field['id']
                                );
                                break;

                            case 'select':
                                $input = sprintf(
                                    '&lt;select id="%s" name="%s"&gt;',
                                    $meta_field['id'],
                                    $meta_field['id']
                                );
                                foreach ( $meta_field['options'] as $key =&gt; $value ) {
                                    $meta_field_value = !is_numeric( $key ) ? $key : $value;
                                    $input .= sprintf(
                                        '&lt;option %s value="%s"&gt;%s&lt;/option&gt;',
                                        $meta_value === $meta_field_value ? 'selected' : '',
                                        $meta_field_value,
                                        $value
                                    );
                                }
                                $input .= '&lt;/select&gt;';
                                break;

                    case 'radio':
                        $input = '&lt;fieldset&gt;';
                        $input .= '&lt;legend class="screen-reader-text"&gt;' . $meta_field['label'] . '&lt;/legend&gt;';
                        $i = 0;
                        foreach ( $meta_field['options'] as $key =&gt; $value ) {
                            $meta_field_value = !is_numeric( $key ) ? $key : $value;
                            $input .= sprintf(
                                '&lt;label&gt;&lt;input %s id=" %s" name="%s" type="radio" value="%s"&gt; %s&lt;/label&gt;%s',
                                $meta_value === $meta_field_value ? 'checked' : '',
                                $meta_field['id'],
                                $meta_field['id'],
                                $meta_field_value,
                                $value,
                                $i &lt; count( $meta_field['options'] ) - 1 ? '&lt;br&gt;' : ''
                            );
                            $i++;
                        }
                        $input .= '&lt;/fieldset&gt;';
                        break;

                            case 'checkbox':
                                $input = sprintf(
                                    '&lt;input %s id=" %s" name="%s" type="checkbox" value="1"&gt;',
                                    $meta_value === '1' ? 'checked' : '',
                                    $meta_field['id'],
                                    $meta_field['id']
                                    );
                                break;

                            case 'textarea':
                                $input = sprintf(
                                    '&lt;textarea style="" id="%s" name="%s" rows="5"&gt;%s&lt;/textarea&gt;',
                                    $meta_field['id'],
                                    $meta_field['id'],
                                    $meta_value
                                );
                                break;

            default:
                                $input = sprintf(
                                    '&lt;input %s id="%s" name="%s" type="%s" value="%s"&gt;',
                                    $meta_field['type'] !== 'color' ? 'style="width: 100%"' : '',
                                    $meta_field['id'],
                                    $meta_field['id'],
                                    $meta_field['type'],
                                    $meta_value
                                );
        }
        $output .= $this-&gt;format_rows( $label, $input );
    }
    echo '&lt;table class="form-table"&gt;&lt;tbody&gt;' . $output . '&lt;/tbody&gt;&lt;/table&gt;';
}

public function format_rows( $label, $input ) {
    return '&lt;tr&gt;&lt;th&gt;'.$label.'&lt;/th&gt;&lt;td&gt;'.$input.'&lt;/td&gt;&lt;/tr&gt;';
}

public function save_fields( $post_id ) {
    if ( ! isset( $_POST['PostExtraField_nonce'] ) )
        return $post_id;
    $nonce = $_POST['PostExtraField_nonce'];
    if ( !wp_verify_nonce( $nonce, 'PostExtraField_data' ) )
        return $post_id;
    if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE )
        return $post_id;
    foreach ( $this-&gt;meta_fields as $meta_field ) {
        if ( isset( $_POST[ $meta_field['id'] ] ) ) {
            switch ( $meta_field['type'] ) {
                case 'email':
                    $_POST[ $meta_field['id'] ] = sanitize_email( $_POST[ $meta_field['id'] ] );
                    break;
                case 'text':
                    $_POST[ $meta_field['id'] ] = sanitize_text_field( $_POST[ $meta_field['id'] ] );
                    break;
            }
            update_post_meta( $post_id, $meta_field['id'], $_POST[ $meta_field['id'] ] );
        } else if ( $meta_field['type'] === 'checkbox' ) {
            update_post_meta( $post_id, $meta_field['id'], '0' );
        }
    }
}

}

if (class_exists(‘PostExtraFieldMetabox’)) { new PostExtraFieldMetabox; };

Dashboard Widget

// Add Custom Dashboard Widget
function add_custom_dashboard_widgets() {
wp_add_dashboard_widget(
    'dk_custom_widget',
    'DK Custom Widget',
    'dashboard_widget_function'
);

// Forcing Widget to top
global $wp_meta_boxes;
$normal_dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
$dk_custom_widget_backup = array( 'dk_custom_widget' =&gt; $normal_dashboard['dk_custom_widget'] );
unset( $normal_dashboard['dk_custom_widget'] );
$sorted_dashboard = array_merge( $dk_custom_widget_backup, $normal_dashboard );
$wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;

} add_action( ‘wp_dashboard_setup’, ‘add_custom_dashboard_widgets’ );

function dashboard_widget_function() {

// Display whatever you want to show.
echo "Hi WordPress, I'm a custom Dashboard Widget";

}

Custom Taxonomy

// Register Taxonomy Gener
// Taxonomy Key: gener
function create_gener_tax() {
    $labels = array(
        'name'              => _x( 'Geners', 'taxonomy general name', 'dukeyin' ),
        'singular_name'     => _x( 'Gener', 'taxonomy singular name', 'dukeyin' ),
        'search_items'      => __( 'Search Geners', 'dukeyin' ),
        'all_items'         => __( 'All Geners', 'dukeyin' ),
        'parent_item'       => __( 'Parent Gener', 'dukeyin' ),
        'parent_item_colon' => __( 'Parent Gener:', 'dukeyin' ),
        'edit_item'         => __( 'Edit Gener', 'dukeyin' ),
        'update_item'       => __( 'Update Gener', 'dukeyin' ),
        'add_new_item'      => __( 'Add New Gener', 'dukeyin' ),
        'new_item_name'     => __( 'New Gener Name', 'dukeyin' ),
        'menu_name'         => __( 'Gener', 'dukeyin' ),
    );
$args = array(
    'labels' =&gt; $labels,
    'description' =&gt; __( 'The description', 'dukeyin' ),
    'hierarchical' =&gt; false,
    'public' =&gt; true,
    'publicly_queryable' =&gt; true,
    'show_ui' =&gt; true,
    'show_in_menu' =&gt; true,
    'show_in_nav_menus' =&gt; true,
    'show_tagcloud' =&gt; true,
    'show_in_quick_edit' =&gt; true,
    'show_admin_column' =&gt; false,
    'show_in_rest' =&gt; true,
);
register_taxonomy( 'gener', array('post','page'), $args );

} add_action( ‘init’, ‘create_gener_tax’ );

User Contact Methods

// Register User Contact Methods
function modify_user_contact_methods( $user_contact ) { 
    // Add user contact methods
    $user_contact['qq']   = __( 'QQ number', 'dukeyin' );
    $user_contact['wechat']   = __( 'Wechat ID', 'dukeyin' );

    // Remove user contact methods
    unset( $user_contact['website'] );
return $user_contact;

} add_filter( ‘user_contactmethods’, ‘modify_user_contact_methods’ );

Login Form

$args = array(
        'value_remember' => 'false',
        'remember' => 'true',
        'echo' => 'true',
        'redirect' => 'https://www.dukeyin.com',
        'form_id' => 'formid',
        'label_username' => 'User Name',
        'label_password' => 'Password',
        'label_remember' => 'Remember me',
        'label_log_in' => 'Login',
        'id_username' => 'username',
        'id_password' => 'psswd',
        'id_remember' => 'rem',
        'id_submit' => 'submit',
        'value_username' => 'duke',
    );
    wp_login_form($args);

Setting/option page

// Settings Page: DukeOptions
// Retrieving values: get_option( 'your_field_id' )
class DukeOptions_Settings_Page {
public function __construct() {
    add_action( 'admin_menu', array( $this, 'wph_create_settings' ) );
    add_action( 'admin_init', array( $this, 'wph_setup_sections' ) );
    add_action( 'admin_init', array( $this, 'wph_setup_fields' ) );
            add_action( 'admin_footer', array( $this, 'media_fields' ) );
    add_action( 'admin_enqueue_scripts', 'wp_enqueue_media' );
}

public function wph_create_settings() {
    $page_title = 'Duke Options';
    $menu_title = 'Duke Options';
    $capability = 'manage_options';
    $slug = 'DukeOptions';
    $callback = array($this, 'wph_settings_content');
            $icon = 'dashicons-arrow-right';
    $position = 2;
    add_menu_page($page_title, $menu_title, $capability, $slug, $callback, $icon, $position);

}

public function wph_settings_content() { ?&gt;
    &lt;div class="wrap"&gt;
        &lt;h1&gt;Duke Options&lt;/h1&gt;
        &lt;?php settings_errors(); ?&gt;
        &lt;form method="POST" action="options.php"&gt;
            &lt;?php
                settings_fields( 'DukeOptions' );
                do_settings_sections( 'DukeOptions' );
                submit_button();
            ?&gt;
        &lt;/form&gt;
    &lt;/div&gt; &lt;?php
}

public function wph_setup_sections() {
    add_settings_section( 'DukeOptions_section', 'Options that demo the use of setting', array(), 'DukeOptions' );
}

public function wph_setup_fields() {
    $fields = array(
                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'Text Field',
                    'placeholder' =&gt; 'placeholder',
                    'id' =&gt; 'textfield',
                    'desc' =&gt; 'the text field',
                    'type' =&gt; 'text',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'Text Area',
                    'placeholder' =&gt; 'placeholder',
                    'id' =&gt; 'textarea',
                    'desc' =&gt; 'the textarea',
                    'type' =&gt; 'textarea',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'WYSIWYG',
                    'placeholder' =&gt; 'rich text',
                    'id' =&gt; 'wysiwyg',
                    'desc' =&gt; 'rich text area',
                    'type' =&gt; 'wysiwyg',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'Check BOX',
                    'placeholder' =&gt; 'checkbox',
                    'id' =&gt; 'checkbox',
                    'desc' =&gt; 'checkbox',
                    'type' =&gt; 'checkbox',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'Radio',
                    'id' =&gt; 'radio',
                    'desc' =&gt; 'radio',
                    'type' =&gt; 'radio',
                    'options' =&gt; array(
                        'first',
                        'second',
                        'last'
                    )
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'Select',
                    'id' =&gt; 'select',
                    'desc' =&gt; 'select',
                    'type' =&gt; 'select',
                    'options' =&gt; array(
                        'first',
                        'second',
                        'last'
                    )
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'media',
                    'id' =&gt; 'media',
                    'desc' =&gt; 'media',
                    'type' =&gt; 'media',
                    'returnvalue' =&gt; 'id'
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'mediaurl',
                    'id' =&gt; 'mediaurl',
                    'desc' =&gt; 'mediaurl',
                    'type' =&gt; 'media',
                    'returnvalue' =&gt; 'url'
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'muilt select',
                    'id' =&gt; 'multiselect',
                    'desc' =&gt; 'muilt select',
                    'type' =&gt; 'multiselect',
                    'options' =&gt; array(
                        'first',
                        'second',
                        'last'
                    )
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'User',
                    'id' =&gt; 'user',
                    'desc' =&gt; 'userselect',
                    'type' =&gt; 'users',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'email',
                    'id' =&gt; 'email',
                    'desc' =&gt; 'email',
                    'type' =&gt; 'email',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'URL',
                    'id' =&gt; 'url',
                    'desc' =&gt; 'url',
                    'type' =&gt; 'url',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'password',
                    'id' =&gt; 'password',
                    'desc' =&gt; 'password',
                    'type' =&gt; 'password',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'number',
                    'id' =&gt; 'number',
                    'desc' =&gt; 'number',
                    'type' =&gt; 'number',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'Color',
                    'placeholder' =&gt; '#eee',
                    'id' =&gt; 'color',
                    'desc' =&gt; 'color',
                    'type' =&gt; 'color',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'Telephone',
                    'id' =&gt; 'tel',
                    'desc' =&gt; 'telephone',
                    'type' =&gt; 'tel',
                ),

                array(
                    'section' =&gt; 'DukeOptions_section',
                    'label' =&gt; 'date',
                    'id' =&gt; 'date',
                    'desc' =&gt; 'date select',
                    'type' =&gt; 'date',
                )
    );
    foreach( $fields as $field ){
        add_settings_field( $field['id'], $field['label'], array( $this, 'wph_field_callback' ), 'DukeOptions', $field['section'], $field );
        register_setting( 'DukeOptions', $field['id'] );
    }
}
public function wph_field_callback( $field ) {
    $value = get_option( $field['id'] );
    $placeholder = '';
    if ( isset($field['placeholder']) ) {
        $placeholder = $field['placeholder'];
    }
    switch ( $field['type'] ) {

                    case 'media':
                        $field_url = '';
                        if ($value) {
                            if ($field['returnvalue'] == 'url') {
                                $field_url = $value;
                            } else {
                                $field_url = wp_get_attachment_url($value);
                            }
                        }
                        printf(
                            '&lt;input style="display:none;" id="%s" name="%s" type="text" value="%s"  data-return="%s"&gt;&lt;div id="preview%s" style="margin-right:10px;border:1px solid #e2e4e7;background-color:#fafafa;display:inline-block;width: 100px;height:100px;background-image:url(%s);background-size:cover;background-repeat:no-repeat;background-position:center;"&gt;&lt;/div&gt;&lt;input style="width: 19%%;margin-right:5px;" class="button menutitle-media" id="%s_button" name="%s_button" type="button" value="Select" /&gt;&lt;input style="width: 19%%;" class="button remove-media" id="%s_buttonremove" name="%s_buttonremove" type="button" value="Clear" /&gt;',
                            $field['id'],
                            $field['id'],
                            $value,
                            $field['returnvalue'],
                            $field['id'],
                            $field_url,
                            $field['id'],
                            $field['id'],
                            $field['id'],
                            $field['id']
                        );
                        break;

                    case 'select':
                        case 'multiselect':
                            if( ! empty ( $field['options'] ) &amp;&amp; is_array( $field['options'] ) ) {
                                $attr = '';
                                $options = '';
                                foreach( $field['options'] as $key =&gt; $label ) {
                                    $options.= sprintf('&lt;option value="%s" %s&gt;%s&lt;/option&gt;',
                                        $key,
                                        selected($value, $key, false),
                                        $label
                                    );
                                }
                                if( $field['type'] === 'multiselect' ){
                                    $attr = ' multiple="multiple" ';
                                }
                                printf( '&lt;select name="%1$s" id="%1$s" %2$s&gt;%3$s&lt;/select&gt;',
                                    $field['id'],
                                    $attr,
                                    $options
                                );
                            }
                            break;

                    case 'radio':
                        if( ! empty ( $field['options'] ) &amp;&amp; is_array( $field['options'] ) ) {
                            $options_markup = '';
                            $iterator = 0;
                            foreach( $field['options'] as $key =&gt; $label ) {
                                $iterator++;
                                $options_markup.= sprintf('&lt;label for="%1$s_%6$s"&gt;&lt;input id="%1$s_%6$s" name="%1$s" type="%2$s" value="%3$s" %4$s /&gt; %5$s&lt;/label&gt;&lt;br/&gt;',
                                $field['id'],
                                $field['type'],
                                $key,
                                checked($value, $key, false),
                                $label,
                                $iterator
                                );
                                }
                                printf( '&lt;fieldset&gt;%s&lt;/fieldset&gt;',
                                $options_markup
                                );
                        }
                        break;

                    case 'checkbox':
                        printf('&lt;input %s id="%s" name="%s" type="checkbox" value="1"&gt;',
                            $value === '1' ? 'checked' : '',
                            $field['id'],
                            $field['id']
                    );
                        break;

                    case 'wysiwyg':
                        wp_editor($value, $field['id']);
                        break;

                    case 'textarea':
                        printf( '&lt;textarea name="%1$s" id="%1$s" placeholder="%2$s" rows="5" cols="50"&gt;%3$s&lt;/textarea&gt;',
                            $field['id'],
                            $placeholder,
                            $value
                            );
                            break;

        default:
            printf( '&lt;input name="%1$s" id="%1$s" type="%2$s" placeholder="%3$s" value="%4$s" /&gt;',
                $field['id'],
                $field['type'],
                $placeholder,
                $value
            );
    }
    if( isset($field['desc']) ) {
        if( $desc = $field['desc'] ) {
            printf( '&lt;p class="description"&gt;%s &lt;/p&gt;', $desc );
        }
    }
}

public function media_fields() {
    ?&gt;&lt;script&gt;
        jQuery(document).ready(function($){
            if ( typeof wp.media !== 'undefined' ) {
                var _custom_media = true,
                _orig_send_attachment = wp.media.editor.send.attachment;
                $('.menutitle-media').click(function(e) {
                    var send_attachment_bkp = wp.media.editor.send.attachment;
                    var button = $(this);
                    var id = button.attr('id').replace('_button', '');
                    _custom_media = true;
                        wp.media.editor.send.attachment = function(props, attachment){
                        if ( _custom_media ) {
                            if ($('input#' + id).data('return') == 'url') {
                                $('input#' + id).val(attachment.url);
                            } else {
                                $('input#' + id).val(attachment.id);
                            }
                            $('div#preview'+id).css('background-image', 'url('+attachment.url+')');
                        } else {
                            return _orig_send_attachment.apply( this, [props, attachment] );
                        };
                    }
                    wp.media.editor.open(button);
                    return false;
                });
                $('.add_media').on('click', function(){
                    _custom_media = false;
                });
                $('.remove-media').on('click', function(){
                    var parent = $(this).parents('td');
                    parent.find('input[type="text"]').val('');
                    parent.find('div').css('background-image', 'url()');
                });
            }
        });
    &lt;/script&gt;&lt;?php
}

} new DukeOptions_Settings_Page();