Duke Yin's Technology database

WordPress Code Snippets

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' => __( 'Tiney' ),
) );
}

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 = 'yduke@hotmail.com';
$subject = 'Welcom to my site';
$headers[] = 'Content-Type: text/html; charset=UTF-8';
$headers[] = 'From: DukeYin <duke@dd.com>';
$message = 'Your message';
wp_mail( $to, $subject, $message);

Register Nav Menu

function dk_register_nav_menus() {
$locations = array(
'primary-menu' => __( 'Primary Menu', 'dukeyin' ),
'secondary-menu' => __( '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' => '3600',
'color' => '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'          => __( 'Left Side bar', 'dukeyin' ),
'description'   => __( 'The left sidebar', 'dukeyin' ),
'id'            => 'leftsidebar',
'class'         => 'leftside',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget'  => '</li>',
'before_title'  => '<h2 class="widgettitle">',
'after_title'   => '</h2>',
);
register_sidebar($args);
$args = array(
'name'          => __( 'Right Side bar', 'dukeyin' ),
'description'   => __( 'The right sidebar', 'dukeyin' ),
'id'            => 'rightsidebar',
'class'         => 'rightside',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget'  => '</li>',
'before_title'  => '<h2 class="widgettitle">',
'after_title'   => '</h2>',
);
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' => 'Text',
'id' => 'textfield',
'default' => 'Default text',
'type' => 'text',
),
array(
'label' => 'Text Area',
'id' => 'textarea',
'default' => 'Defaule texts',
'type' => 'textarea',
),
array(
'label' => 'WYSIWYG',
'id' => 'rich-text',
'default' => 'Deafult text',
'type' => 'wysiwyg',
),
array(
'label' => 'Check box',
'id' => 'checkbox',
'default' => 'true',
'type' => 'checkbox',
),
array(
'label' => 'Radio',
'id' => 'radio',
'default' => 'second',
'type' => 'radio',
'options' => array(
'first',
'second',
'third'
)
),
array(
'label' => 'Select',
'id' => 'select',
'default' => 'second',
'type' => 'select',
'options' => array(
'first',
'second',
'third'
)
),
array(
'label' => 'Media',
'id' => 'media',
'type' => 'media',
'returnvalue' => 'url'
),
array(
'label' => 'Categories',
'id' => 'cat',
'type' => 'categories',
),
array(
'label' => 'User',
'id' => 'user',
'type' => 'users',
),
array(
'label' => 'Email',
'id' => 'email',
'default' => 'yduke@hotmail.com',
'type' => 'email',
),
array(
'label' => 'URL',
'id' => 'url',
'default' => 'https://www.google.com',
'type' => 'url',
),
array(
'label' => 'Password',
'id' => 'pswd',
'type' => 'password',
),
array(
'label' => 'Number',
'id' => 'number',
'default' => '123',
'type' => 'number',
),
array(
'label' => 'Color',
'id' => 'color',
'default' => '#eeeeee',
'type' => 'color',
),
array(
'label' => 'Tel',
'id' => 'tel',
'type' => '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->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->field_generator( $post );
}
public function media_fields() {
?><script>
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()');
});
}
});
</script><?php
}
public function field_generator( $post ) {
$output = '';
foreach ( $this->meta_fields as $meta_field ) {
$label = '<label for="' . $meta_field['id'] . '">' . $meta_field['label'] . '</label>';
$meta_value = get_post_meta( $post->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' => $meta_value,
'echo' => 0,
'name' => $meta_field['id'],
'id' => $meta_field['id'],
'show_option_none' => 'Select a user',
);
$input = wp_dropdown_users($usersargs);
break;
case 'categories':
$categoriesargs = array(
'selected' => $meta_value,
'hide_empty' => 0,
'echo' => 0,
'name' => $meta_field['id'],
'id' => $meta_field['id'],
'show_option_none' => '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(
'<input style="display:none;" id="%s" name="%s" type="text" value="%s"  data-return="%s"><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;"></div><input style="width: 19%%;margin-right:5px;" class="button new-media" id="%s_button" name="%s_button" type="button" value="Select" /><input style="width: 19%%;" class="button remove-media" id="%s_buttonremove" name="%s_buttonremove" type="button" value="Clear" />',
$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(
'<select id="%s" name="%s">',
$meta_field['id'],
$meta_field['id']
);
foreach ( $meta_field['options'] as $key => $value ) {
$meta_field_value = !is_numeric( $key ) ? $key : $value;
$input .= sprintf(
'<option %s value="%s">%s</option>',
$meta_value === $meta_field_value ? 'selected' : '',
$meta_field_value,
$value
);
}
$input .= '</select>';
break;
case 'radio':
$input = '<fieldset>';
$input .= '<legend class="screen-reader-text">' . $meta_field['label'] . '</legend>';
$i = 0;
foreach ( $meta_field['options'] as $key => $value ) {
$meta_field_value = !is_numeric( $key ) ? $key : $value;
$input .= sprintf(
'<label><input %s id=" %s" name="%s" type="radio" value="%s"> %s</label>%s',
$meta_value === $meta_field_value ? 'checked' : '',
$meta_field['id'],
$meta_field['id'],
$meta_field_value,
$value,
$i < count( $meta_field['options'] ) - 1 ? '<br>' : ''
);
$i++;
}
$input .= '</fieldset>';
break;
case 'checkbox':
$input = sprintf(
'<input %s id=" %s" name="%s" type="checkbox" value="1">',
$meta_value === '1' ? 'checked' : '',
$meta_field['id'],
$meta_field['id']
);
break;
case 'textarea':
$input = sprintf(
'<textarea style="" id="%s" name="%s" rows="5">%s</textarea>',
$meta_field['id'],
$meta_field['id'],
$meta_value
);
break;
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s">',
$meta_field['type'] !== 'color' ? 'style="width: 100%"' : '',
$meta_field['id'],
$meta_field['id'],
$meta_field['type'],
$meta_value
);
}
$output .= $this->format_rows( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
public function format_rows( $label, $input ) {
return '<tr><th>'.$label.'</th><td>'.$input.'</td></tr>';
}
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' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->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' => $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' => $labels,
'description' => __( 'The description', 'dukeyin' ),
'hierarchical' => false,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
'show_in_quick_edit' => true,
'show_admin_column' => false,
'show_in_rest' => 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() { ?>
<div class="wrap">
<h1>Duke Options</h1>
<?php settings_errors(); ?>
<form method="POST" action="options.php">
<?php
settings_fields( 'DukeOptions' );
do_settings_sections( 'DukeOptions' );
submit_button();
?>
</form>
</div> <?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' => 'DukeOptions_section',
'label' => 'Text Field',
'placeholder' => 'placeholder',
'id' => 'textfield',
'desc' => 'the text field',
'type' => 'text',
),
array(
'section' => 'DukeOptions_section',
'label' => 'Text Area',
'placeholder' => 'placeholder',
'id' => 'textarea',
'desc' => 'the textarea',
'type' => 'textarea',
),
array(
'section' => 'DukeOptions_section',
'label' => 'WYSIWYG',
'placeholder' => 'rich text',
'id' => 'wysiwyg',
'desc' => 'rich text area',
'type' => 'wysiwyg',
),
array(
'section' => 'DukeOptions_section',
'label' => 'Check BOX',
'placeholder' => 'checkbox',
'id' => 'checkbox',
'desc' => 'checkbox',
'type' => 'checkbox',
),
array(
'section' => 'DukeOptions_section',
'label' => 'Radio',
'id' => 'radio',
'desc' => 'radio',
'type' => 'radio',
'options' => array(
'first',
'second',
'last'
)
),
array(
'section' => 'DukeOptions_section',
'label' => 'Select',
'id' => 'select',
'desc' => 'select',
'type' => 'select',
'options' => array(
'first',
'second',
'last'
)
),
array(
'section' => 'DukeOptions_section',
'label' => 'media',
'id' => 'media',
'desc' => 'media',
'type' => 'media',
'returnvalue' => 'id'
),
array(
'section' => 'DukeOptions_section',
'label' => 'mediaurl',
'id' => 'mediaurl',
'desc' => 'mediaurl',
'type' => 'media',
'returnvalue' => 'url'
),
array(
'section' => 'DukeOptions_section',
'label' => 'muilt select',
'id' => 'multiselect',
'desc' => 'muilt select',
'type' => 'multiselect',
'options' => array(
'first',
'second',
'last'
)
),
array(
'section' => 'DukeOptions_section',
'label' => 'User',
'id' => 'user',
'desc' => 'userselect',
'type' => 'users',
),
array(
'section' => 'DukeOptions_section',
'label' => 'email',
'id' => 'email',
'desc' => 'email',
'type' => 'email',
),
array(
'section' => 'DukeOptions_section',
'label' => 'URL',
'id' => 'url',
'desc' => 'url',
'type' => 'url',
),
array(
'section' => 'DukeOptions_section',
'label' => 'password',
'id' => 'password',
'desc' => 'password',
'type' => 'password',
),
array(
'section' => 'DukeOptions_section',
'label' => 'number',
'id' => 'number',
'desc' => 'number',
'type' => 'number',
),
array(
'section' => 'DukeOptions_section',
'label' => 'Color',
'placeholder' => '#eee',
'id' => 'color',
'desc' => 'color',
'type' => 'color',
),
array(
'section' => 'DukeOptions_section',
'label' => 'Telephone',
'id' => 'tel',
'desc' => 'telephone',
'type' => 'tel',
),
array(
'section' => 'DukeOptions_section',
'label' => 'date',
'id' => 'date',
'desc' => 'date select',
'type' => '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(
'<input style="display:none;" id="%s" name="%s" type="text" value="%s"  data-return="%s"><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;"></div><input style="width: 19%%;margin-right:5px;" class="button menutitle-media" id="%s_button" name="%s_button" type="button" value="Select" /><input style="width: 19%%;" class="button remove-media" id="%s_buttonremove" name="%s_buttonremove" type="button" value="Clear" />',
$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'] ) && is_array( $field['options'] ) ) {
$attr = '';
$options = '';
foreach( $field['options'] as $key => $label ) {
$options.= sprintf('<option value="%s" %s>%s</option>',
$key,
selected($value, $key, false),
$label
);
}
if( $field['type'] === 'multiselect' ){
$attr = ' multiple="multiple" ';
}
printf( '<select name="%1$s" id="%1$s" %2$s>%3$s</select>',
$field['id'],
$attr,
$options
);
}
break;
case 'radio':
if( ! empty ( $field['options'] ) && is_array( $field['options'] ) ) {
$options_markup = '';
$iterator = 0;
foreach( $field['options'] as $key => $label ) {
$iterator++;
$options_markup.= sprintf('<label for="%1$s_%6$s"><input id="%1$s_%6$s" name="%1$s" type="%2$s" value="%3$s" %4$s /> %5$s</label><br/>',
$field['id'],
$field['type'],
$key,
checked($value, $key, false),
$label,
$iterator
);
}
printf( '<fieldset>%s</fieldset>',
$options_markup
);
}
break;
case 'checkbox':
printf('<input %s id="%s" name="%s" type="checkbox" value="1">',
$value === '1' ? 'checked' : '',
$field['id'],
$field['id']
);
break;
case 'wysiwyg':
wp_editor($value, $field['id']);
break;
case 'textarea':
printf( '<textarea name="%1$s" id="%1$s" placeholder="%2$s" rows="5" cols="50">%3$s</textarea>',
$field['id'],
$placeholder,
$value
);
break;
default:
printf( '<input name="%1$s" id="%1$s" type="%2$s" placeholder="%3$s" value="%4$s" />',
$field['id'],
$field['type'],
$placeholder,
$value
);
}
if( isset($field['desc']) ) {
if( $desc = $field['desc'] ) {
printf( '<p class="description">%s </p>', $desc );
}
}
}
public function media_fields() {
?><script>
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()');
});
}
});
</script><?php
}
}
new DukeOptions_Settings_Page();

发布评论

评论

标注 * 的为必填项。