Is there any function in Wordpress that allows to hide the gravatar if id doesn't exists?
I have many authors that doesn't have a gravatar and all are displayed like this:
http://prntscr.com/98zsji
I would like to hide the default image.
I used the function validate_gravatar($email);, but it generated an error:
Fatal error: Call to undefined function validate_gravatar()
If I print $user_email it display correctly the user email.
You can use validate_gravatar which takes in the email address of the user and returns back true or false.
validate_gravatar($email); // returns true or false
How to use it in your code:
$user_email = get_the_author_meta('user_email');
if(validate_gravatar($user_email)) {
$author_avatar = get_avatar( get_the_author_meta( 'user_email', $author_id ), '78', '', get_the_author_meta( 'display_name', $author_id ) );
}
// Now just echo where ever you want the image, it will show a default image if no gravatar is present.
if(isset($author_avatar) && !empty($author_avatar)){
echo '<img src="'.$author_avatar.'" />';
}
// In your Functions.php
function validate_gravatar($email) {
$hash = md5(strtolower(trim($email)));
$uri = 'http://www.gravatar.com/avatar/' . $hash . '?d=404';
$headers = #get_headers($uri);
if (!preg_match("|200|", $headers[0])) {
$has_valid_avatar = FALSE;
} else {
$has_valid_avatar = TRUE;
}
return $has_valid_avatar;
}
Here is the filter that will do the trick:
function ns_filter_avatar($avatar, $id_or_email, $size, $default, $alt, $args)
{
$headers = #get_headers( $args['url'] );
if( ! preg_match("|200|", $headers[0] ) ) {
return;
}
return $avatar;
}
add_filter('get_avatar','ns_filter_avatar', 10, 6);
To work you have to add value 404 as third argument $default to get_avatar(). Example:
get_avatar( $user_email, 45, '404' )
I have been using the code below for a while and always work for me. The code is checked with PHPCS and WordPress Theme Standards and there is no errors or warnings.
The script profile-image.js is only enqueued on the respective page user-edit.php, that also applies for the media-upload and Thickbox scripts, this procedure will avoid any possible scripts conflict on your WordPress admin area.
/**
*
* Add custom user profile information
*
*/
add_action( 'show_user_profile', 'ns_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'ns_show_extra_profile_fields' );
function ns_show_extra_profile_fields( $user ) { ?>
<h3>Extra profile information</h3>
<table class="form-table">
<tr>
<th><label for="image">Profile Image</label></th>
<td>
<img src="<?php echo esc_attr( get_the_author_meta( 'image', $user->ID ) ); ?>" style="height:50px;">
<input type="text" name="image" id="image" value="<?php echo esc_attr( get_the_author_meta( 'image', $user->ID ) ); ?>" class="regular-text" /><input type='button' class="button-primary" value="Upload Image" id="uploadimage"/><br />
<span class="description">Please upload your image for your profile.</span>
</td>
</tr>
</table>
<?php
}
/**
* Enqueue a script in the WordPress admin user-edit.php.
*
* #param int $pagenow Hook suffix for the current admin page.
*/
function ns_selectively_enqueue_admin_script( $hook ) {
global $pagenow;
if ($pagenow != 'user-edit.php') {
return;
}
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_style('thickbox');
wp_register_script( 'profile-image', get_template_directory_uri().'/js/profile-image.js', array('jquery-core'), false, true );
wp_enqueue_script( 'profile-image' );
}
add_action( 'admin_enqueue_scripts', 'ns_selectively_enqueue_admin_script' );
/*
* Save custom user profile data
*
*/
add_action( 'personal_options_update', 'ns_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'ns_save_extra_profile_fields' );
function ns_save_extra_profile_fields( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
return false;
if(isset($_POST['image'])) {
$imageprofile = sanitize_text_field( wp_unslash( $_POST['image'] ) );
update_user_meta( $user_id, 'image', $imageprofile );
}
}
profile-image.js:
jQuery(document).ready(function() {
jQuery(document).find("input[id^='uploadimage']").live('click', function(){
//var num = this.id.split('-')[1];
formfield = jQuery('#image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
window.send_to_editor = function(html) {
imgurl = jQuery('img',html).attr('src');
jQuery('#image').val(imgurl);
tb_remove();
}
return false;
});
});
Related
I have a custom user profile field "association_id". I can see the field the underlying wordpess db table (usermeta) with the 'meta_key' as "association_id" and the 'meta_value' whatever that I maintain for each user.
add_action( 'show_user_profile', 'rudr_profile_fields' );
add_action( 'edit_user_profile', 'rudr_profile_fields' );
function rudr_profile_fields( $user )
{
// let's get custom field values
$association_id = get_user_meta( $user->ID, 'association_id', true );
?>
<h3>Association Information</h3>
<table class="form-table">
<tr>
<th><label for="association_id">Association_ID</label></th>
<td>
<input type="text" name="association_id" id="association_id" value="<?php echo esc_attr( $association_id ) ?>" class="regular-text" />
<span class="description"><?php _e("Please enter your Association ID (For eg. if RCIC, your license number)."); ?></span>
</td>
</tr>
</table>
<?php
}
//avoid self to edit //
//add_action( 'personal_options_update', 'rudr_save_profile_fields' ); //
add_action( 'edit_user_profile_update', 'rudr_save_profile_fields' );
function rudr_save_profile_fields( $user_id ) {
if( ! isset( $_POST[ '_wpnonce' ] ) || ! wp_verify_nonce( $_POST[ '_wpnonce' ], 'update-user_' . $user_id ) ) {
return;
}
if( ! current_user_can( 'edit_user', $user_id ) ) {
return;
}
/* HOLDING SPACE FOR ENHANCED SNIPPED */
//include in the list view of users
add_filter( 'manage_users_columns', 'column_register_association_id' );
add_filter( 'manage_users_custom_column', 'column_display_association_id', 10, 3 );
function column_register_association_id( $columns )
{
$columns['association_id'] = 'association_id';
return $columns;
}
function column_display_association_id( $value, $column_name, $user_id )
{
$user_info = get_user_meta( $user_id, 'association_id', true );
if($column_name == 'association_id') return $user_info;
return $value;
}
//Sort association_id column
function association_id_register_sortable( $columns ) {
$columns['association_id'] = 'association_id';
return $columns;
}
add_filter( 'manage_users_sortable_columns', 'association_id_register_sortable' );
function association_id_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'association_id' == $vars['orderby'] ) {
$vars = array_merge( $vars, array(
'meta_key' => 'association_id',
'orderby' => 'meta_value'
) );
}
return $vars;
}
add_filter( 'request', 'association_id_orderby' );
The preceding works fine and creates a meta key for storing meta value in the metadata wp table.
I want this custom user profile field value that I enter in the user admin page to be unique, verifying with the underlying wordpress database table. So I enhanced the code at the time of creation with the additional lines below. I tried these two snippets in the wordpress child theme, but it throws a critical error. I am on PHP version 8.
I tried two options below at the placeholder location in the above code, replacing the line below.
/* HOLDING SPACE FOR ENHANCED SNIPPED */
Option 1 that I tried.
$checkMeta=$wpdb->get_results("SELECT user_id FROM $wpdb->usermeta WHERE meta_key='association_id' AND meta_value=".$association_id,ARRAY_A);
if (empty($checkMeta)) {
update_user_meta( $user_id, 'association_id', sanitize_text_field( $_POST[ 'association_id' ] ) );
}
Option 2 that I tried.
$mysqli = new mysqli(SERVER, DBUSER, DBPASS, DATABASE); $result = $mysqli->query("SELECT user_id FROM usermeta WHERE meta_key='association_id' && meta_value=$association_id "); if($result->num_rows == 0) { // row not found, do stuff update_user_meta( $user_id, 'association_id', sanitize_text_field( $_POST[ 'association_id' ] ) ); } else { // row found, do stuff echo ' This ID is already used.'; } $mysqli->close();
Both failed to activate when I tried to create or change the 'association_field' value, throwing critical errors and aborting.
I'm adding a pretty basic (I feel) implementation of settings page validation for my WordPress plugin and it does work, but the error messages are shown twice. I stepped through my code and the calls to add_settings_error are only executed once.
<?php
class Example_plugin_Settings {
private $example_plugin_settings_options;
private $settings_options_name;
public function __construct() {
add_action( 'admin_menu', array( $this, 'example_plugin_settings_add_plugin_page' ) );
add_action( 'admin_init', array( $this, 'example_plugin_settings_page_init' ) );
$this->settings_options_name = 'example_plugin_options';
}
public function example_plugin_settings_add_plugin_page() {
add_options_page(
'Example-Plugin Connector Settings', // page_title
'Example-Plugin', // menu_title
'manage_options', // capability
'example-plugin-connector-settings', // menu_slug
array( $this, 'example_plugin_settings_create_admin_page' ) // function
);
}
public function example_plugin_settings_create_admin_page() {
$this->example_plugin_settings_options = get_option( 'example_plugin_options' ); ?>
<div class="wrap">
<h2>Example-Plugin Connector Settings</h2>
<p>Set up additional portals/currencies to be used with WooCommerce Currency Switcher (WOOCS). Enter a comma-delimited list of portals, then the corresponding comma-delimited list of currencies that those portals support.</p>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields( 'example_plugin_settings_option_group' );
do_settings_sections( 'example-plugin-connector-settings-admin' );
submit_button();
?>
</form>
</div>
<?php }
public function example_plugin_settings_page_init() {
register_setting(
'example_plugin_settings_option_group', // option_group
$this->settings_options_name, // option_name
array( $this, 'example_plugin_settings_sanitize' ) // sanitize_callback
);
add_settings_section(
'example_plugin_settings_setting_section', // id
'Settings', // title
array( $this, 'example_plugin_settings_section_info' ), // callback
'example-plugin-connector-settings-admin' // page
);
add_settings_field(
'portals', // id
'Portals', // title
array( $this, 'portals_callback' ), // callback
'example-plugin-connector-settings-admin', // page
'example_plugin_settings_setting_section' // section
);
add_settings_field(
'currencies', // id
'Currencies', // title
array( $this, 'currencies_callback' ), // callback
'example-plugin-connector-settings-admin', // page
'example_plugin_settings_setting_section' // section
);
}
public function example_plugin_settings_sanitize($input) {
$sanitary_values = array();
if ( isset( $input['portals'] ) ) {
if ( '' == $input['portals'] ) {
$input['portals'] = '';
add_settings_error(
$this->settings_options_name,
'portals',
'Portals is a required field.',
'error'
);
} else {
$sanitary_values['portals'] = sanitize_text_field( trim( $input['portals'] ) );
}
}
if ( isset( $input['currencies'] ) ) {
if ( '' == $input['currencies'] ) {
$input['currencies'] = '';
add_settings_error(
$this->settings_options_name,
'currencies',
'Currencies is a required field.',
'error'
);
} else {
$sanitary_values['currencies'] = sanitize_text_field( trim( $input['currencies'] ) );
}
}
return $sanitary_values;
}
public function example_plugin_settings_section_info() {
}
public function portals_callback() {
printf(
'<input class="regular-text" type="text" name="example_plugin_options[portals]" id="portals" value="%s">',
isset( $this->example_plugin_settings_options['portals'] ) ? esc_attr( $this->example_plugin_settings_options['portals']) : ''
);
}
public function currencies_callback() {
printf(
'<input class="regular-text" type="text" name="example_plugin_options[currencies]" id="currencies" value="%s">',
isset( $this->example_plugin_settings_options['currencies'] ) ? esc_attr( $this->example_plugin_settings_options['currencies']) : ''
);
}
}
if ( is_admin() )
$example_plugin_settings = new Example_plugin_Settings();
It seems the problem is the line <?php settings_errors(); ?>. I got the base code from the WordPress Options Page Generator but maybe the code is outdated and that line is now redundant with newer versions of WordPress? I'm not sure.
I am trying to implement multiple select product using select2 . the list come up using getproductsearch this ajax action i did earlier but i failed to save it. I did this feature before for post-meta and product-category but failed for plugin option page. I am not sure what i am doing wrong.
please help.
class FeatureSale {
private $feature_sale_options;
public function __construct() {
add_action( 'admin_menu', array( $this, 'feature_sale_add_plugin_page' ) );
add_action( 'admin_init', array( $this, 'feature_sale_page_init' ) );
}
public function feature_sale_add_plugin_page() {
add_submenu_page(
'exclutips-settings',
'Feature & Sale', // page_title
'Feature & Sale', // menu_title
'manage_options', // capability
'feature-sale', // menu_slug
array( $this, 'feature_sale_create_admin_page' ) // function
);
}
public function feature_sale_create_admin_page() {
$this->feature_sale_options = get_option( 'feature_sale_option_name' ); ?>
<div class="wrap">
<div class="catbox-area-admin" style="width: 500px;background: #fff;padding: 27px 50px;">
<h2>Feature & Sale</h2>
<p></p>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields( 'feature_sale_option_group' );
do_settings_sections( 'feature-sale-admin' );
submit_button();
?>
</form>
</div>
</div>
<?php }
public function feature_sale_page_init() {
register_setting(
'feature_sale_option_group', // option_group
'feature_sale_option_name', // option_name
array( $this, 'feature_sale_sanitize' ) // sanitize_callback
);
add_settings_section(
'feature_sale_setting_section', // id
'', // title
array( $this, 'feature_sale_section_info' ), // callback
'feature-sale-admin' // page
);
add_settings_field(
'vpm_sale_product', // id
'VPM Sale Product', // title
array( $this, 'vpm_sale_product_callback' ), // callback
'feature-sale-admin', // page
'feature_sale_setting_section' // section
);
add_settings_field(
'vpm_featured_product', // id
'VPM Featured Product', // title
array( $this, 'vpm_featured_product_callback' ), // callback
'feature-sale-admin', // page
'feature_sale_setting_section' // section
);
}
public function feature_sale_sanitize($input) {
$sanitary_values = array();
if ( isset( $input['vpm_sale_product'] ) ) {
$sanitary_values['vpm_sale_product'] = $input['vpm_sale_product'];
}
if ( isset( $input['vpm_featured_product'] ) ) {
$sanitary_values['vpm_featured_product'] = $input['vpm_featured_product'];
}
return $sanitary_values;
}
public function feature_sale_section_info() {
}
//Output the HTML for the metabox.
public function vpm_sale_product_callback() {
global $post;
// Nonce field to validate form request came from current site
wp_nonce_field( basename( __FILE__ ), 'vpm_sale_product_nonce' );
$html = '';
// always array because we have added [] to our <select> name attribute
$feature_sale_options = get_option( 'feature_sale_option_name' ); // Array of All Options
$vpm_sale_product = $feature_sale_options['vpm_sale_product'];
$html .= '<p><select id="vpm_sale_product" name="vpm_sale_product[]" multiple="multiple" style="width:99%;max-width:25em;">';
if( $vpm_sale_product ) {
foreach( $vpm_sale_product as $post_id ) {
$title = get_the_title( $post_id );
// if the post title is too long, truncate it and add "..." at the end
$title = ( mb_strlen( $title ) > 50 ) ? mb_substr( $title, 0, 49 ) . '...' : $title;
$html .= '<option value="' . $post_id . '" selected="selected">' . $title . '</option>';
}
}
$html .= '</select></p>';
echo $html;
//==========================================
}
//* Output the HTML for the metabox.
public function vpm_featured_product_callback() {
global $post;
// Nonce field to validate form request came from current site
wp_nonce_field( basename( __FILE__ ), 'vpm_featured_product_nonce' );
$html = '';
// always array because we have added [] to our <select> name attribute
$feature_sale_options = get_option( 'feature_sale_option_name' ); // Array of All Options
$vpm_featured_product = $feature_sale_options['vpm_featured_product'];
$html .= '<p><select id="vpm_featured_product" name="vpm_featured_product[]" multiple="multiple" style="width:99%;max-width:25em;">';
if( $vpm_featured_product ) {
foreach( $vpm_featured_product as $post_id ) {
$title = get_the_title( $post_id );
// if the post title is too long, truncate it and add "..." at the end
$title = ( mb_strlen( $title ) > 50 ) ? mb_substr( $title, 0, 49 ) . '...' : $title;
$html .= '<option value="' . $post_id . '" selected="selected">' . $title . '</option>';
}
}
$html .= '</select></p>';
echo $html;
echo $vpm_featured_product;
//==========================================
?>
<script>
(function ($) {
'use strict';
$(function () {
//--------------------------------------------------------------------------
// multiple select with AJAX search
$('#vpm_featured_product,#vpm_sale_product').select2({
ajax: {
url: ajaxurl, // AJAX URL is predefined in WordPress admin
dataType: 'json',
delay: 250, // delay in ms while typing when to perform a AJAX search
data: function (params) {
return {
q: params.term, // search query
action: 'getproductsearch' // AJAX action for admin-ajax.php
};
},
processResults: function( data ) {
var options = [];
if ( data ) {
// data is the array of arrays, and each of them contains ID and the Label of the option
$.each( data, function( index, text ) { // do not forget that "index" is just auto incremented value
options.push( { id: text[0], text: text[1] } );
});
}
return {
results: options
};
},
cache: true
},
minimumInputLength: 3 // the minimum of symbols to input before perform a search
});
//----------------------------------------------------------------------------------------
});
})(jQuery);
</script>
<?php
}
}
if ( is_admin() )
$feature_sale = new FeatureSale();
The problem is that these select tags are not using the correct name value:
<select id="vpm_sale_product" name="vpm_sale_product[]"...>
<select id="vpm_featured_product" name="vpm_featured_product[]"...>
And the proper name values are: (based on your register_setting() call)
<select id="vpm_sale_product" name="feature_sale_option_name[vpm_sale_product][]"...>
<select id="vpm_featured_product" name="feature_sale_option_name[vpm_featured_product][]"...>
And although after correcting the above issue, the form data would be saved properly, the fifth parameter (i.e. the menu/page slug) passed to add_submenu_page() should match the fourth parameter passed to add_settings_section() and add_settings_field(), and also the one passed to do_settings_sections(). In your add_submenu_page() call, the menu/page slug is feature-sale, but with the other three functions, you set it to feature-sale-admin.
And using wp_nonce_field() is recommended, but in your case, it's not necessary since you're submitting to wp-admin/options.php. Unless of course, you want to check that prior to WordPress saving the options. But even so, I believe one nonce field is good. :)
I am using wordpress 4.7.2
I am trying to create a simple widget that will only help user to upload an image .
Below my code, when I am selecting an image , it gives me option to insert into post, but I want it not be associated to any post, just want its url and id so that I can use it to display.
I tried to follow use media upload in custom widget and create image uploader widget and wordpress custom widget image uplaaod but could not solved it.
<?php
namespace MyTheme\Widgets;
use \MyTheme\Widgets as Widgets;
class Image extends \WP_Widget {
public function __construct( $id_base = false, $name = false, $widget_options = array(), $control_options = array() ) {
$id_base = ( $id_base ) ? $id_base : 'mytheme-widget-image';
$name = ( $name ) ? $name : __( 'Image', 'mytheme-widget-image-i18n' );
$widget_options = wp_parse_args( $widget_options, array(
'classname' => 'widget_image',
'description' => __( 'An image from the media library', 'mytheme-widget-image-i18n' )
) );
$control_options = wp_parse_args( $control_options, array( 'width' => 300 ) );
parent::__construct( $id_base, $name, $widget_options, $control_options );
add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') );
}
public function widget( $args, $instance ) {
$content = $this->render( $args, $wp_widget );
}
public function render( $args, $instance ){
//generate content
return $content;
}
public function form($instance){
$widget_img_id = isset($instance['widget_img_id']) ? $instance['widget_img_id'] : '';
$image_src = isset($instance['widget-img-id']) ? $instance['widget-img-id'] : '';
$upload_link = esc_url( get_upload_iframe_src( 'image', $widget_img_id ) );
$is_image = ! empty($image_src);
?>
<div class="widget-img-wrapper">
<div class="widget-img-container">
<?php if ( $is_image ): ?>
<img src="<?php echo $image_src; ?>" alt="" style="max-width:100%" />
<?php endif; ?>
<p class="hide-if-no-js">
<a name="upload_img_src" href="<?php echo $upload_link; ?>" class="upload-widget-img <?php if ( $is_image ){ echo 'hidden'; } ?>">
<?php _e('Set custom image') ?>
</a>
<a class="delete-widget-img <?php if ( ! $is_image ) { echo 'hidden'; } ?>"
href="#">
<?php _e('Remove this image') ?>
</a>
<input class="widget-img-id" name="widget_img_id" type="hidden" value="<?php echo esc_attr( $image_id ); ?>" />
</p>
</div>
</div>
<?php
}
public function update( $new_instance, $old_instance ){
$instance = array();
$instance['widget_img_id'] = ( ! empty( $new_instance['widget_img_id'] ) ) ? strip_tags( $new_instance['widget_img_id'] ) : '';
$instance['upload_img_src'] = ( ! empty( $new_instance['upload_img_src'] ) ) ? strip_tags( $new_instance['upload_img_src'] ) : '';
return $instance;
}
public static function print_footer_js()
{
wp_enqueue_media();
?>
<script>
jQuery(function($){
// Set all variables to be used in scope
var frame,
imageContainer = $('.widget-img-wrapper'), // Your meta box id here
addImgLink = imageContainer.find('.upload-widget-img'),
delImgLink = imageContainer.find( '.delete-widget-img'),
imgContainer = imageContainer.find( '.widget-img-container'),
imgIdInput = imageContainer.find( '.widget-img-id' );
// ADD IMAGE LINK
addImgLink.on( 'click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create a new media frame
frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: {
text: 'Use this media'
},
library: {
type: 'image'
}
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected in the media frame...
frame.on( 'select', function() {
// Get media attachment details from the frame state
var attachment = frame.state().get('selection').first().toJSON();
// Send the attachment URL to our custom image input field.
imgContainer.append( '<img src="'+attachment.url+'" alt="" style="max-width:100%;"/>' );
// Send the attachment id to our hidden input
imgIdInput.val( attachment.id );
// Hide the add image link
addImgLink.addClass( 'hidden' );
// Unhide the remove image link
delImgLink.removeClass( 'hidden' );
});
// Finally, open the modal on click
frame.open();
});
// DELETE IMAGE LINK
delImgLink.on( 'click', function( event ){
event.preventDefault();
// Clear out the preview image
imgContainer.html( '' );
// Un-hide the add image link
addImgLink.removeClass( 'hidden' );
// Hide the delete image link
delImgLink.addClass( 'hidden' );
// Delete the image id from the hidden input
imgIdInput.val( '' );
});
});
</script>
<?php
}
}
I believe, taht "insert into post" is just the default text, and that it doesn't really have anything to do with the post - The file ends up in the media library and in the uploads folders anyway -
function replace_window_text($translated_text, $text) {
if ('Insert into Post' == $text) {
$referer = strpos(wp_get_referer(), 'media_page');
if ($referer != '') {
return __('Upload Billede', 'ink');
}
}
return $translated_text;
}
This is from one of my old projects, where I created a plugin for media uploading. probably doesn't fit your problem, but it can maybe put you on the right path
The issue with this is
add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') ); is unable to enqueue script, neither wp_footer, admin_footer or admin_enqueue_scripts will be able to render script, need to enqueue outside the class. that solves my problem. Do not use this javascript, has problem with instance as used class in js.
<?php
namespace MyTheme\Widgets;
use \MyTheme\Widgets as Widgets;
class Image extends \WP_Widget {
public function __construct( $id_base = false, $name = false, $widget_options = array(), $control_options = array() ) {
$id_base = ( $id_base ) ? $id_base : 'mytheme-widget-image';
$name = ( $name ) ? $name : __( 'Image', 'mytheme-widget-image-i18n' );
$widget_options = wp_parse_args( $widget_options, array(
'classname' => 'widget_image',
'description' => __( 'An image from the media library', 'mytheme-widget-image-i18n' )
) );
$control_options = wp_parse_args( $control_options, array( 'width' => 300 ) );
parent::__construct( $id_base, $name, $widget_options, $control_options );
add_action('image_widget_print_footer_scripts', array(__CLASS__, 'print_footer_js') );
}
public function widget( $args, $instance ) {
$content = $this->render( $args, $wp_widget );
}
public function render( $args, $instance ){
//generate content
return $content;
}
public function form($instance){
$widget_img_id = isset($instance['widget_img_id']) ? $instance['widget_img_id'] : '';
$image_src = isset($instance['widget-img-id']) ? $instance['widget-img-id'] : '';
$upload_link = esc_url( get_upload_iframe_src( 'image', $widget_img_id ) );
$is_image = ! empty($image_src);
?>
<div class="widget-img-wrapper">
<div class="widget-img-container">
<?php if ( $is_image ): ?>
<img src="<?php echo $image_src; ?>" alt="" style="max-width:100%" />
<?php endif; ?>
<p class="hide-if-no-js">
<a name="upload_img_src" href="<?php echo $upload_link; ?>" class="upload-widget-img <?php if ( $is_image ){ echo 'hidden'; } ?>">
<?php _e('Set custom image') ?>
</a>
<a class="delete-widget-img <?php if ( ! $is_image ) { echo 'hidden'; } ?>"
href="#">
<?php _e('Remove this image') ?>
</a>
<input class="widget-img-id" name="widget_img_id" type="hidden" value="<?php echo esc_attr( $image_id ); ?>" />
</p>
</div>
</div>
<?php
}
public function update( $new_instance, $old_instance ){
$instance = array();
$instance['widget_img_id'] = ( ! empty( $new_instance['widget_img_id'] ) ) ? strip_tags( $new_instance['widget_img_id'] ) : '';
$instance['upload_img_src'] = ( ! empty( $new_instance['upload_img_src'] ) ) ? strip_tags( $new_instance['upload_img_src'] ) : '';
return $instance;
}
}
and JS
add_action( 'admin_enqueue_scripts', function(){
wp_enqueue_media('jquery');
} );
add_action('admin_footer', function(){
?>
<script>
jQuery(function($){
// Set all variables to be used in scope
var frame,
imageContainer = $('.widget-img-wrapper'), // Your meta box id here
addImgLink = imageContainer.find('.upload-widget-img'),
delImgLink = imageContainer.find( '.delete-widget-img'),
imgContainer = imageContainer.find( '.widget-img-container'),
imgIdInput = imageContainer.find( '.widget-img-id' );
// ADD IMAGE LINK
addImgLink.on( 'click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create a new media frame
frame = wp.media({
title: 'Select or Upload Media Of Your Chosen Persuasion',
button: {
text: 'Use this media'
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected in the media frame...
frame.on( 'select', function() {
// Get media attachment details from the frame state
var attachment = frame.state().get('selection').first().toJSON();
// Send the attachment URL to our custom image input field.
imgContainer.append( '<img src="'+attachment.url+'" alt="" style="max-width:100%;"/>' );
// Send the attachment id to our hidden input
imgIdInput.val( attachment.id );
// Hide the add image link
addImgLink.addClass( 'hidden' );
// Unhide the remove image link
delImgLink.removeClass( 'hidden' );
});
// Finally, open the modal on click
frame.open();
});
// DELETE IMAGE LINK
delImgLink.on( 'click', function( event ){
event.preventDefault();
// Clear out the preview image
imgContainer.html( '' );
// Un-hide the add image link
addImgLink.removeClass( 'hidden' );
// Hide the delete image link
delImgLink.addClass( 'hidden' );
// Delete the image id from the hidden input
imgIdInput.val( '' );
});
});
</script>
<?php
}
I have created a settings page for my wordpress plugin as described in codex (https://codex.wordpress.org/Creating_Options_Pages) #Example 2. My question is how to add tabbed options (tab interface) for WordPress Plugin Settings page for #Example 2 on WP codex?
I have created a Setting page for my plugin with 'Composer Autoload'
but for now, I am sharing just simple class to show how
my plugin has the setting page two tabs
'PDF Setting Tab'
'Email Setting Tab'
if ( ! class_exists( 'Plugin_Name_Settings_Page' ) ) {
class Plugin_Name_Settings_Page {
/* Admin Parent Menu item - properties */
private $page_title;
private $menu_title;
private $capability;
private $menu_slug;
private $function;
private $icon_url;
private $position;
public $page_menu;
public function __construct() {
$this->page_title = 'Plugin_Name Settings';
$this->menu_title = 'Plugin_Name Settings';
$this->capability = 'manage_options'; //'edit_pages';
$this->menu_slug = 'Plugin_Name-settings-page'; //'Plugin_Name-admin-dashboard';
$this->function = array( $this, 'page' );
$this->icon_url = 'dashicons-cart';
$this->position = 24;
// Create Admin Page & Menu
add_action( 'admin_menu', array( $this, 'CreatePageMenu' ), 10 );
add_action( 'Plugin_Name_settings_page_created', array( $this, 'Plugin_Name_pdf_settings_init' ), 10 );
}
public function CreatePageMenu() {
$this->page_menu = add_menu_page(
$this->page_title,
$this->menu_title,
$this->capability,
$this->menu_slug,
$this->function,
$this->icon_url,
$this->position,
);
do_action( 'Plugin_Name_settings_page_created' );
}
public function page() {
?>
<div class="wrap">
<!-- Create a header in the default WordPress 'wrap' container -->
<div id="icon-themes" class="icon32"></div>
<h2>Plugin_Name Settings</h2>
<?php settings_errors(); ?>
<?php
if ( isset( $_GET ) ) {
$active_tab = $_GET['tab'];
}
?>
<h2 class="nav-tab-wrapper">
PDF Settings
Email Settings
</h2>
<form method="post" action="options.php">
<?php
if ( $active_tab == 'pdf_settings' ) {
// settings options group name passed
settings_fields( 'Plugin_Name_pdf_settings_options_group' );
// settings options name passed
do_settings_sections( 'Plugin_Name_pdf_settings_options' );
submit_button();
} elseif ( $active_tab == 'email_settings' ) {
// settings options group name passed
settings_fields( 'Plugin_Name_email_settings_options_group' );
// settings options name passed
do_settings_sections( 'Plugin_Name_email_settings_options' );
submit_button();
}
?>
</form>
</div><!-- /.wrap -->
<?php
}
/***** Start - Tab 01 - PDF Settings Script ***/
public function plugin_name_pdf_settings_init() {
register_setting(
'plugin_name_pdf_settings_options_group', // option_group
'plugin_name_pdf_settings_options', // option_name
array( $this, 'plugin_name_pdf_settings_options_sanitize' ), // sanitize_callback
);
add_settings_section(
'plugin_name_pdf_settings_options_section', // id
'plugin_name PDF Settings', // title
array( $this, 'plugin_name_pdf_settings_options_section_info' ), // callback
//'plugin_name-admin-dashboard', //$_GET['page'], // page
'plugin_name_pdf_settings_options'
);
add_settings_field(
'plugin_name_enrollment_agent_name_option', // id
'Enrollment Agent Name', // title
array( $this, 'plugin_name_enrollment_agent_name_option_callback' ), // callback
'plugin_name_pdf_settings_options', // page
'plugin_name_pdf_settings_options_section' // section
);
add_settings_field(
'plugin_name_enrollment_agent_cert_option', // id
'Enrollment Agent Cert #', // title
array( $this, 'plugin_name_enrollment_agent_cert_option_callback' ), // callback
'plugin_name_pdf_settings_options', // page
'plugin_name_pdf_settings_options_section' // section
);
add_settings_field(
'plugin_name_enrollment_accepted_by_option', // id
'Enrollment Accepted By', // title
array( $this, 'plugin_name_enrollment_accepted_by_option_callback' ), // callback
'plugin_name_pdf_settings_options', // page
'plugin_name_pdf_settings_options_section' // section
);
}
public function plugin_name_pdf_settings_options_section_info() {
echo 'plugin_name PDF Settings, admin can set fix daat for PDF.';
}
public function plugin_name_pdf_settings_options_sanitize( $input ) {
$sanitary_values = array();
if ( isset( $input['plugin_name_enrollment_agent_name_option'] ) ) {
$sanitary_values['plugin_name_enrollment_agent_name_option'] = $input['plugin_name_enrollment_agent_name_option'];
}
if ( isset( $input['plugin_name_enrollment_agent_cert_option'] ) ) {
$sanitary_values['plugin_name_enrollment_agent_cert_option'] = $input['plugin_name_enrollment_agent_cert_option'];
}
if ( isset( $input['plugin_name_enrollment_accepted_by_option'] ) ) {
$sanitary_values['plugin_name_enrollment_accepted_by_option'] = $input['plugin_name_enrollment_accepted_by_option'];
}
return $sanitary_values;
}
function plugin_name_enrollment_agent_name_option_callback() {
$plugin_name_pdf_option_agent_name_value = ( isset($this->plugin_name_pdf_settings_options['plugin_name_enrollment_agent_name_option'] ) ) ? $this->plugin_name_pdf_settings_options['plugin_name_enrollment_agent_name_option']: '';
?>
<input type="text" name="plugin_name_pdf_settings_options[plugin_name_enrollment_agent_name_option]" value="<?php echo $plugin_name_pdf_option_agent_name_value; ?>">
<?php
}
function plugin_name_enrollment_agent_cert_option_callback() {
$plugin_name_pdf_option_agent_cert_value = ( isset($this->plugin_name_pdf_settings_options['plugin_name_enrollment_agent_cert_option'] ) ) ? $this->plugin_name_pdf_settings_options['plugin_name_enrollment_agent_cert_option']: '';
?>
<input type="text" name="plugin_name_pdf_settings_options[plugin_name_enrollment_agent_cert_option]" value="<?php echo $plugin_name_pdf_option_agent_cert_value; ?>">
<?php
}
function plugin_name_enrollment_accepted_by_option_callback() {
$plugin_name_pdf_option_accepted_by_value = ( isset($this->plugin_name_pdf_settings_options['plugin_name_enrollment_accepted_by_option'] ) ) ? $this->plugin_name_pdf_settings_options['plugin_name_enrollment_accepted_by_option']: '';
?>
<input type="text" name="plugin_name_pdf_settings_options[plugin_name_enrollment_accepted_by_option]" value="<?php echo $plugin_name_pdf_option_accepted_by_value; ?>">
<?php
}
/*** End - Tab 01 - PDF Settings Script ***/
/**** STart - Tab 02 - Email Settings Script ***/
public function plugin_name_email_settings_init() {
register_setting(
'plugin_name_email_settings_options_group', // option_group
'plugin_name_email_settings_options', // option_name
array( $this, 'plugin_name_email_settings_options_sanitize' ), // sanitize_callback
);
add_settings_section(
'plugin_name_email_settings_options_section', // id
'plugin_name email Settings', // title
array( $this, 'plugin_name_email_settings_options_section_info' ), // callback
//'plugin_name-admin-dashboard', //$_GET['page'], // page
'plugin_name_email_settings_options'
);
add_settings_field(
'plugin_name_teacher_name_option', // id
'Enrollment Agent Name', // title
array( $this, 'plugin_name_teacher_name_option_callback' ), // callback
'plugin_name_email_settings_options', // page
'plugin_name_email_settings_options_section' // section
);
add_settings_field(
'plugin_name_teacher_cert_option', // id
'Enrollment Agent Cert #', // title
array( $this, 'plugin_name_teacher_cert_option_callback' ), // callback
'plugin_name_email_settings_options', // page
'plugin_name_email_settings_options_section' // section
);
add_settings_field(
'plugin_name_room_number_option', // id
'Enrollment Accepted By', // title
array( $this, 'plugin_name_room_number_option_callback' ), // callback
'plugin_name_email_settings_options', // page
'plugin_name_email_settings_options_section' // section
);
}
public function plugin_name_email_settings_options_section_info() {
echo 'plugin_name email Settings, admin can set fix daat for email.';
}
public function plugin_name_email_settings_options_sanitize( $input ) {
$sanitary_values = array();
if ( isset( $input['plugin_name_teacher_name_option'] ) ) {
$sanitary_values['plugin_name_teacher_name_option'] = $input['plugin_name_teacher_name_option'];
}
if ( isset( $input['plugin_name_teacher_cert_option'] ) ) {
$sanitary_values['plugin_name_teacher_cert_option'] = $input['plugin_name_teacher_cert_option'];
}
if ( isset( $input['plugin_name_room_number_option'] ) ) {
$sanitary_values['plugin_name_room_number_option'] = $input['plugin_name_room_number_option'];
}
return $sanitary_values;
}
function plugin_name_teacher_name_option_callback() {
$plugin_name_email_option_agent_name_value = ( isset($this->plugin_name_email_settings_options['plugin_name_teacher_name_option'] ) ) ? $this->plugin_name_email_settings_options['plugin_name_teacher_name_option']: '';
?>
<input type="text" name="plugin_name_email_settings_options[plugin_name_teacher_name_option]" value="<?php echo $plugin_name_email_option_agent_name_value; ?>">
<?php
}
function plugin_name_teacher_cert_option_callback() {
$plugin_name_email_option_agent_cert_value = ( isset($this->plugin_name_email_settings_options['plugin_name_teacher_cert_option'] ) ) ? $this->plugin_name_email_settings_options['plugin_name_teacher_cert_option']: '';
?>
<input type="text" name="plugin_name_email_settings_options[plugin_name_teacher_cert_option]" value="<?php echo $plugin_name_email_option_agent_cert_value; ?>">
<?php
}
function plugin_name_room_number_option_callback() {
$plugin_name_email_option_accepted_by_value = ( isset($this->plugin_name_email_settings_options['plugin_name_room_number_option'] ) ) ? $this->plugin_name_email_settings_options['plugin_name_room_number_option']: '';
?>
<input type="text" name="plugin_name_email_settings_options[plugin_name_room_number_option]" value="<?php echo $plugin_name_email_option_accepted_by_value; ?>">
<?php
}
/**** End - Tab 02 - Email Settings Script *****/
}
// Class Instence / object call for execution on requiring this page
new Plugin_Name_Settings_Page();
}
I found this tutorial online. Hope this helps.
http://plugin.michael-simpson.com/?page_id=47