how to add text widgets to wordpress sidebar using function? - php

I want to add text widget into my site sidebar when I activate theme. How can I do this using wordpress function or other methods? I'm using wordpress 4.1.
Help me. Thanks.

I don't know that what kind of widget you want to create, so i give you a simple example so you can understand.
Write blow code in functions.php or create an external file and include it into functions.php
First Register the Widget:
//========= Your Custom Widget
add_action( 'widgets_init', 'your_simple_widget' );
function your_simple_widget() {
register_widget( 'Your_Simple_Same_Widget' );
}
Second Create a widget body:
class Your_Simple_Same_Widget extends WP_Widget { }
NOTE: register_widget( 'Your_Simple_Same_Widget' ); name and class Your_Simple_Same_Widget and widget setup name must be same
There are four parts of widget in class
Widget Setup
How to display on front end
Update Widget values
Widget form or fields in admin panel
Ok Third in class Write this code like:
//========= Your Custom Widget Body
class Your_Simple_Same_Widget extends WP_Widget {
//=======> Widget setup
function Your_Simple_Same_Widget() {
/* Widget settings. */
$widget_ops = array( 'classname' => 'your class', 'description' => __('Your Class Description widget', 'your class') );
/* Widget control settings. */
$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'your_widget' );
/* Create the widget. */
$this->WP_Widget( 'your_widget', __('Widget Heading', 'your class'), $widget_ops, $control_ops );
}
//=======> How to display the widget on the screen.
function widget($args, $widgetData) {
extract($args);
//=======> Our variables from the widget settings.
$your_widget_title = $widgetData['txtYourTitle'];
$your_widget_description = $widgetData['txtYourDescription'];
//=======> widget body
echo $before_widget;
echo '<div class="">';
if($your_widget_title){
echo '<h2>'.$your_widget_title .'</h2>';
}
if($your_widget_description){
echo '<p>'.$your_widget_description .'</p>';
}
echo "</div>";
echo $after_widget;
}
//=======>Update the widget
function update($new_widgetData, $old_widgetData) {
$widgetData = $old_widgetData;
//Strip tags from title and name to remove HTML
$widgetData['txtYourTitle'] = $new_widgetData['txtYourTitle'];
$widgetData['txtYourDescription'] = $new_widgetData['txtYourDescription'];
return $widgetData;
}
//=======>widget Display
function form($widgetData) {
//Set up some default widget settings.
$widgetData = wp_parse_args((array) $widgetData);
?>
<p>
<label for="<?php echo $this->get_field_id('txtYourTitle'); ?>">Widget Title:</label>
<input id="<?php echo $this->get_field_id('txtYourTitle'); ?>" name="<?php echo $this->get_field_name('txtYourTitle'); ?>" value="<?php echo $widgetData['txtYourTitle']; ?>" style="width:275px;" />
</p>
<p>
<label for="<?php echo $this->get_field_id('txtYourDescription'); ?>">Widget Title:</label>
<input id="<?php echo $this->get_field_id('txtYourDescription'); ?>" name="<?php echo $this->get_field_name('txtYourDescription'); ?>" value="<?php echo $widgetData['txtYourDescription']; ?>" style="width:275px;" />
</p>
<?php
}
}
?>
I hope this may help you.

Related

My WordPress plugin does not work properly in user section

I wrote a very simple code that is supposed to read several fields from the WordPress admin section and display them on the page where I put the company code, but the problem is that only the field changes are displayed for the admin and the user sees no changes. Does not
I have two of them in my plugin that I put php code here
Part One: admin-page.php
if ( isset($_POST['submit']) ) {
$currency_update_date = isset($_POST['turksend_currency_update_date']) ? $_POST['turksend_currency_update_date'] : '';
update_option('turksend_currency_update_date', $currency_update_date);
}
<form method="POST">
<table class="form-table">
<tr>
<th scope="row">
<label for="turksend_currency_update_date">Date Update</label>
</th>
<td>
<input name="turksend_currency_update_date" type="text" id="turksend_currency_update_date" value="<?php echo get_option('turksend_currency_update_date', ''); ?>" class="regular-text code">
</td>
</tr>
<tr>
</table>
<p class="submit">
<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php _e('Save Changes'); ?>">
</p>
</form>
Part two: turksend-calculator.php
<?php
/**
* Plugin Name: ....
* Plugin URI: ....
* Description: .....
* Version: 1.0
* Author: ...
* Author URI: .....
*/
global $turksend_db_version;
$turksend_db_version = '1.0';
/* Install plugin - Create options */
function turksend_install() {
global $turksend_db_version;
add_option( 'turksend_db_version', $turksend_db_version );
add_option( 'turksend_currency_update_date', '' );
}
register_activation_hook( __FILE__, 'turksend_install' );
/* Uninstall plugin - Delete options */
function turksend_uninstall() {
global $turksend_db_version;
delete_option( 'turksend_db_version' );
delete_option( 'turksend_currency_update_date' );
}
register_deactivation_hook( __FILE__, 'turksend_uninstall' );
register_uninstall_hook( __FILE__, 'turksend_uninstall' );
/* Add admin menu page */
function turksend_init() {
require_once plugin_dir_path(__FILE__) . 'admin-page.php';
}
function turksend_register_options_page() {
add_menu_page(
'Calculate',
'Calculate',
'manage_options',
'turksend',
'turksend_init',
'dashicons-plus'
);
}
add_action('admin_menu', 'turksend_register_options_page');
/* Add plugin page settings link */
add_filter('plugin_action_links_'.plugin_basename(__FILE__), 'turksend_add_plugin_page_settings_link');
function turksend_add_plugin_page_settings_link ( $links ) {
$links[] = '' . __('Settings') . '';
return $links;
}
function turksend_canculate() {
echo get_option('turksend_currency_update_date');
}
add_shortcode('turksend-canculate', 'turksend_canculate');
Everything is correct, changes are not displayed only for users who are not logged in to the site
function turksend_canculate() {
echo get_option('turksend_currency_update_date');
}
you have an error, you must return data, not print
function bartag_func( $atts ) {
$a = shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts );
return "foo = {$a['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );
https://codex.wordpress.org/Shortcode_API

WordPress Options Page function visibility

i am currently setting up an options page in wordpress for my plugin. Why is it not possible to implement the functions as protected or private? The class is directly instantiated. As far as is know, it is possible with java as object oriented language to make them protected in this scenario, isn´t it?
Do i have to implement the $this variable generally with array or is this wordpress specific? It works right now and i have found some comments in the doc claiming that it has to me made this way, but i don´t understand why it´s necessary.
I know this is mostly basic php knowledge, but that´s why i am asking - to learn. Thanks for any help
<?php
class SettingsPage {
static $optionGroup = 'juvo_option_group';
static $optionTitle = 'JUVO Anpassungen';
public function __construct() {
// create custom plugin settings menu
add_action('admin_menu', array( $this, 'my_cool_plugin_create_menu'));
//call register settings function
add_action( 'admin_init', array( $this, 'register_juvo_plugin_settings' ));
}
public function my_cool_plugin_create_menu() {
//create new top-level menu
add_options_page(
self::$optionTitle, //Page Title
self::$optionTitle, //Menu Title
'manage_options', //required Capabilities
'juvo-setting', //Slug
array( $this, 'juvo_settings_page')
);
}
public function register_juvo_plugin_settings() {
//register our settings
register_setting( self::$optionGroup, 'privacy_policy_comments' );
}
public function juvo_settings_page() {
?>
<div class="wrap">
<h1><?php echo self::$optionTitle ?></h1>
<form method="post" action="options.php">
<?php settings_fields( self::$optionGroup );
$options = get_option( 'privacy_policy_comments' );
do_settings_sections( self::$optionGroup ); ?>
<table class="form-table">
<tr valign="top">
<th scope="row">Seitentitel Datenschutzerklärung</th>
<td><input type="text" name="privacy_policy_comments[title]" value="<?php echo esc_attr( $options['title']); ?>" /></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php }
}
if( is_admin() )
$my_settings_page = new SettingsPage();

Add shortcode to TinyMCE for show menu dropdown

I have a shortcode for show menu:
//menu categories shortcode
function menu_categories_shortcode( $atts, $content = null ){
extract( shortcode_atts( array(
'menu' => ''
), $atts ) );
ob_start();
wp_nav_menu(array(
'menu' => $menu,
'container' => 'ul',
'container_class' => 'sidebar-categories',
'items_wrap' => '%3$s',
'depth' => 1
));
$content = ob_get_contents();
ob_end_clean();
return $content;
}
add_shortcode('menu-categories', 'menu_categories_shortcode');
Now, i wanna add shortcode button of menu shortcode to TinyMCE for client can choose menu they want to show.
Ex: On Home page, client want to show menu with menu name is Menu 1, so shortcode will be: [menu-categories menu="Menu 1"]
When client click menu shortcode button, a dropdown of all menu will be popup for client can choose menu they want.
This is my js to call menu popup:
(function() {
tinymce.create('tinymce.plugins.menuPlugin', {
init: function(ed, url) {
// Register commands
ed.addCommand('mcebutton', function() {
ed.windowManager.open({
file: url + '/menu_popup.php',
width: 220 + parseInt(ed.getLang('button.delta_width', 0)),
height: 240 + parseInt(ed.getLang('button.delta_height', 0)),
inline: 1
}, {
plugin_url: url
});
});
// Register buttons
ed.addButton('menu_button', {
title: 'Choose Menu',
cmd: 'mcebutton',
image: url + '/icon.gif'
});
},
});
tinymce.PluginManager.add('menu_button', tinymce.plugins.buttonPlugin);
})();
The problem I've in menu_popup.php, how to i get all menus?
My menu_popup.php file:
<form action="/" method="get" accept-charset="utf-8">
<div>
<label for="button-url">Choose Menu</label>
<?php $menus = get_registered_nav_menus();
if($menus) : ?>
<select id="button-url">
<?php
foreach ($menus as $key => $menu) : ?>
<option value="<?php echo $menu; ?>"><?php echo $menu; ?></option> <?php endforeach; ?>
</select>
<?php endif; ?>
</div>
<div>
Insert
</div>
</form>
Error i have:
Thanks so much!!!
In your menu_poup.php you need to include this code:
define('WP_USE_THEMES', false);
require('../../../wp-blog-header.php');
https://codex.wordpress.org/Integrating_WordPress_with_Your_Website
to access WordPress functions. I just tried it using your code and it worked.

WordPress My theme options settings not saving

I just created a simple theme option page that is working fine and also saved after when press save options.
But when I go somewhere else from theme options page and come back to theme options page that settings what I saved just disappear and I have to change that again whenever I come to theme options page.
Here is my code
add_action( 'admin_menu', 'theme_options_add_page' );
if ( get_option('new_theme_options')) {
$theme_options = get_option('new_theme_options');
} else {
add_option('new_theme_options', array (
'sidebar2_on' => true,
'footer_text' => ''
));
$theme_options = get_option('new_theme_options');
}
function theme_options_add_page() {
add_submenu_page( 'themes.php', 'My Theme Options', 'Theme Options', 8, 'themeoptions', 'theme_options_do_page' );
}
function theme_options_do_page() {
global $theme_options;
$new_values = array (
'footer_text' => htmlentities($_POST['footer_text'], ENT_QUOTES),
);
update_option('new_theme_options', $new_values);
$theme_options = $new_values;
?>
<div class="wrap">
<?php screen_icon(); echo "<h2>" . get_current_theme() . __( ' Theme Options', 'responsivetheme' ) . "</h2>"; ?>
<form method="post" action="themes.php?page=themeoptions">
<label for="footer_text">Footer Text:</label>
<input id="footer_text" type="text" name="footer_text" value="<?php echo $theme_options['footer_text']; ?>" />
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'responsivetheme' ); ?>" />
</p>
</form>
</div>
<?php
}
#Praveen answer is correct, but for completeness I'll post the full code I tested. Please, note that you should always develop with WP_DEBUG enabled. It shows three issues with your code:
using $_POST['footer_text'] without it being defined (Praveen's answer)
using the deprecated function get_current_theme()
using Level instead of Capability in add_submenu_page()
I dropped the following code into my theme's functions.php and it works ok:
if ( get_option('new_theme_options')) {
$theme_options = get_option('new_theme_options');
} else {
$theme_options = array (
'sidebar2_on' => true,
'footer_text' => ''
);
add_option( 'new_theme_options', $theme_options );
}
add_action( 'admin_menu', 'theme_options_add_page' );
function theme_options_add_page() {
add_submenu_page(
'themes.php',
'My Theme Options',
'Theme Options',
'add_users',
'themeoptions',
'theme_options_do_page'
);
}
function theme_options_do_page() {
global $theme_options;
if( isset( $_POST['footer_text'] ) ) {
$new_values = array (
'footer_text' => htmlentities( $_POST['footer_text'], ENT_QUOTES),
);
update_option('new_theme_options', $new_values);
$theme_options = $new_values;
}
?>
<div class="wrap">
<?php screen_icon(); echo "<h2>" . wp_get_theme() . __( ' Theme Options', 'responsivetheme' ) . "</h2>"; ?>
<form method="post" action="themes.php?page=themeoptions">
<label for="footer_text">Footer Text:</label>
<input id="footer_text" type="text" name="footer_text" value="<?php echo $theme_options['footer_text']; ?>" />
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'responsivetheme' ); ?>" />
</p>
</form>
</div>
<?php
}
The only issue I can see is the option value sidebar2_on that's being overwritten in theme_options_do_page(), but your sample code does not show it being used elsewhere.
Please change this code:
if($_POST['footer_text']) {
$new_values = array (
'footer_text' => htmlentities($_POST['footer_text'], ENT_QUOTES),
);
update_option('new_theme_options', $new_values);
$theme_options = $new_values;
}
hope this will work fine :)

How to auto activate WordPress widgets? (New Widgets_API WP_Widget class)

I gave up on this finally.
I am developing something on WordPress 2.8.4. I am impressed by the ease of new widgets API which allows you to use extends WP_Widget and create widgets that have multiple instances easily. But I am facing a problem.
How can I auto-activate the widget on theme activation? I've tried to use:
add_action('sidebars_widgets', array('sidebar-1', array('uc_tagcloud')));
But with no success. the problem is that New wordpress API creates widget ids and adds a unique id to the end of ID automatically. So I just can't get the hang of it. I've tried the above solution but the actual widget ID by viewing source code always displays uc_tagcloud-2 or 3 or 4..etc etc.. a new instance every time i add the widget.
I would appreciate any thought, I've deeply thought about it and searched the internet for hours now. So this is my last chance.
I basically do not want users to drag and enable them manually.
Below is a sample widget I've developed. It works fine if i drag and put it in relevant sidebar. But I do not know how .. my question is : how can I activate it automatically into specific sidebar without draggin it manually (WP_Widget new Widgets API)
This is code of widget:
<?php
/**********************************************************************
Widget: Tag Cloud List
**********************************************************************/
class uc_tagcloud extends WP_Widget {
// Constructor
function uc_tagcloud() {
$widget_ops = array('description' => __('A list of your blog tags for your sidebar','ucms'));
$this->WP_Widget('uc_tagcloud', __('ultimaCMS - Tag Cloud','ucms'), $widget_ops);
}
// Display Widget
function widget($args, $instance) {
extract($args);
$title = esc_attr($instance['title']);
$num = intval($instance['num']);
echo $before_widget.$before_title.$title.$after_title;
// Display widget content
?>
<?php wp_tag_cloud('smallest=9&largest=22&number='.$num); ?>
<?php
echo $after_widget;
}
// When Widget Control Form Is Posted
function update($new_instance, $old_instance) {
if (!isset($new_instance['submit'])) {
return false;
}
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['num'] = intval($new_instance['num']);
return $instance;
}
// DIsplay Widget Control Form
function form($instance) {
global $wpdb;
$instance = wp_parse_args((array) $instance, array('title' => __('Tag Cloud','ucms'), 'num' => 100));
$title = esc_attr($instance['title']);
$num = intval($instance['num']);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:','ucms'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('num'); ?>"><?php _e('Number of tags:','ucms'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('num'); ?>" name="<?php echo $this->get_field_name('num'); ?>" type="text" value="<?php echo $num; ?>" />
<br /><small>Enter 0 to display all tags</small>
</p>
<input type="hidden" id="<?php echo $this->get_field_id('submit'); ?>" name="<?php echo $this->get_field_name('submit'); ?>" value="1" />
<?php
}
}
### Initiate widget
add_action('widgets_init', 'uc_tagcloud_init');
function uc_tagcloud_init() {
register_widget('uc_tagcloud');
}
?>
It's very simple, the new API i love it. But I just can't get how to auto activate an instance of the widget on specific sidebar. Any help?
There's a blog post mirror as old as this Question that may have a solution, but it is designed to WordPress MU (now Multisite) and should be updated/adapted accordingly. It is a mix of mu-plugin and extra code in the theme's functions.php.
But based in this Q&A in WordPress Answers and this other blog post no mirror yet, the following works for WordPress 3.3 or superior. It runs on theme activation and is tested with WP 3.4.2 and applied on TwentyEleven's functions.php.
add_action( 'after_switch_theme', 'so_1353147_activate_theme', 10 , 2 );
function so_1353147_activate_theme( $oldname, $oldtheme = false )
{
$sidebar_id = 'sidebar-5';
$sidebars_widgets = get_option( 'sidebars_widgets' );
$id = count( $sidebars_widgets ) + 1;
$sidebars_widgets[$sidebar_id] = array( "text-" . $id );
$ops = get_option( 'widget_text' );
$ops[$id] = array(
'title' => 'Automatic Widget',
'text' => 'Lorem ipsum lorem',
);
update_option( 'widget_text', $ops );
update_option( 'sidebars_widgets', $sidebars_widgets );
}

Categories