Wordpress: Add config option to all widget settings - wordpress

In Wordpress, my goal is to be able to give a custom class to every widget that I put in the sidebar.
Preferably I would like to add this class in the widget settings of each widget. ALSO 3rd party widgets.
I was thinking of changing the classname, because the classname is already passed to the register_sidebar function (%2$s):
<?php
register_sidebar(array('before_widget' => '<aside id="%1$s" class="widget %2$s blue">'));
?>
Ofcourse I shouldn't change WP core code or 3rd party plugins. This means that I need to write a plugin that will hook into the widget configuration process.
I already found out that it's possible to modify all widgets forms, by hooking into action 'in_widget_form':
<?php
add_action('in_widget_form', 'teaserWidgetAddToForm');
function teaserWidgetAddToForm($widget_instance) {
?>
<label for="<?php echo $widget_instance->get_field_id('teaser-classname'); ?>">Custom classname(s):</label>
<input type="text" id="<?php echo $widget_instance->get_field_id('teaser-classname'); ?>" name="<?php echo $widget_instance->get_field_name('teaser-classname'); ?>">
<?php
}
?>
This data should be saved by the Widget super class, but how do you retrieve this data (so when opening the widget settings later shows what you filled in earlier)
And, this saved data should be put in the widget instance -how is this done? I guess by using something like:
<?php
$wp_registered_widgets[<widget_id>]['callback'][0]['widget_options']['classname'] = <chosen_class>;
?>
So basically I have 2 questions:
Am I using the proper way to address this problem (styling of individual widgets)
If so, how can I modify a widget instance to save and retrieve additional settings, without having to modify Wordpress or 3rd party Plugin source code.

By default each widget instance has a unique ID which can be used to style it.
In order to save data from fields added in an in_widget_form action, you need to also have a widget_update_callback filter.
function my_widget_update_callback($instance, $new_instance) {
$instance['my_classnames'] = $new_instance['my_classnames'];
return $instance;
}
To display the saved value in the form you'll need to first retrieve the instance settings.
function my_in_widget_form($instance) {
$settings = $instance->get_settings();
…
Finally, I think the simplest way to add your custom classes is in a widget_display_callback filter, which runs before a widget is displayed. You have to display the widget yourself because you can only return an instance from this filter, and instances do not control the widget CSS classes.
function my_widget_display_callback($instance, $widget, $args) {
if (!isset($instance['my_classnames'])) {
return $instance;
}
$widget_classname = $widget->widget_options['classname'];
$my_classnames = $instance['my_classnames'];
$args['before_widget'] = str_replace($widget_classname, "{$widget_classname} {$my_classnames}", $args['before_widget']);
$widget->widget($args, $instance);
return false;
}
See this article for more info on the available hooks related to widgets: http://shibashake.com/wordpress-theme/wordpress-widget-system

Related

Add custom product field on quick edit option on the product listing of a woocommerce site

How can I add custom product field/s on quick edit screen on the product listing of a woocommerce store?
I am not really sure if this is the best way to do it, but it works great for me
Basically my general goal is to add custom fields for a product, I managed to do it (Adding custom fields to the single product pages) with the help of these useful tuts.
http://www.remicorson.com/mastering-woocommerce-products-custom-fields/
http://www.remicorson.com/woocommerce-custom-fields-for-variations/
I recommend checking those links first before proceeding.
Now, what I wanted to do is to add those custom fields to the quick add option on the product listing.
That's where the resource get scarce.
Basically this is how I did it.
Add your custom field (the html forms) to the quick edit options.
I hooked into the 'woocommerce_product_quick_edit_end' action to accomplish this.
This hook is found on woocommerce->includes->admin->views->html-quick-edit-product.php on line 195
Save your custom field.
I hooked into the 'woocommerce_product_quick_edit_save' action to accomplish this.
This hook is found on woocommerce->includes->admin->class-wc-admin-post-types.php inside the 'quick_edit_save' function on line 929
The previous 2 steps does the trick, it does persist the values, however after updating the custom field via the quick edit option, the data is persisted on the backend, but is not populated to the custom field on the UI. That's why we need the 3rd step.
Add the custom field meta data inside the product listing column, then use js to extract the metadata out then populate it to the custom field
I hooked into the 'manage_product_posts_custom_column' action to add a custom HTML tags (div or whatever) to hold my custom field metadata
Then I used javascript to extract the data out from the meta data and populate it into the custom fields
Step 3 is just a copy of how WooCommerce does this process.
For referrence, take a look at function 'render_product_columns' of woocommerce->includes->admin->class-wc-admin-post-types.php
Also take a look at quick-edit.js located at woocommerce->assets->js->admin
Example Code:
Note that the code below is used for illustration and guide purposes, my actual code is quite long and complex.
Step 1:
add_action( 'woocommerce_product_quick_edit_end', function(){
/*
Notes:
Take a look at the name of the text field, '_custom_field_demo', that is the name of the custom field, basically its just a post meta
The value of the text field is blank, it is intentional
*/
?>
<div class="custom_field_demo">
<label class="alignleft">
<div class="title"><?php _e('Custom Field Demo', 'woocommerce' ); ?></div>
<input type="text" name="_custom_field_demo" class="text" placeholder="<?php _e( 'Custom Field Demo', 'woocommerce' ); ?>" value="">
</label>
</div>
<?php
} );
Step 2:
add_action('woocommerce_product_quick_edit_save', function($product){
/*
Notes:
$_REQUEST['_custom_field_demo'] -> the custom field we added above
Only save custom fields on quick edit option on appropriate product types (simple, etc..)
Custom fields are just post meta
*/
if ( $product->is_type('simple') || $product->is_type('external') ) {
$post_id = $product->id;
if ( isset( $_REQUEST['_custom_field_demo'] ) ) {
$customFieldDemo = trim(esc_attr( $_REQUEST['_custom_field_demo'] ));
// Do sanitation and Validation here
update_post_meta( $post_id, '_custom_field_demo', wc_clean( $customFieldDemo ) );
}
}
}, 10, 1);
Step 3:
add_action( 'manage_product_posts_custom_column', function($column,$post_id){
/*
Notes:
The 99 is just my OCD in action, I just want to make sure this callback gets executed after WooCommerce's
*/
switch ( $column ) {
case 'name' :
?>
<div class="hidden custom_field_demo_inline" id="custom_field_demo_inline_<?php echo $post_id; ?>">
<div id="_custom_field_demo"><?php echo get_post_meta($post_id,'_custom_field_demo',true); ?></div>
</div>
<?php
break;
default :
break;
}
}, 99, 2);
The JS part
jQuery(function(){
jQuery('#the-list').on('click', '.editinline', function(){
/**
* Extract metadata and put it as the value for the custom field form
*/
inlineEditPost.revert();
var post_id = jQuery(this).closest('tr').attr('id');
post_id = post_id.replace("post-", "");
var $cfd_inline_data = jQuery('#custom_field_demo_inline_' + post_id),
$wc_inline_data = jQuery('#woocommerce_inline_' + post_id );
jQuery('input[name="_custom_field_demo"]', '.inline-edit-row').val($cfd_inline_data.find("#_custom_field_demo").text());
/**
* Only show custom field for appropriate types of products (simple)
*/
var product_type = $wc_inline_data.find('.product_type').text();
if (product_type=='simple' || product_type=='external') {
jQuery('.custom_field_demo', '.inline-edit-row').show();
} else {
jQuery('.custom_field_demo', '.inline-edit-row').hide();
}
});
});
Make sure to enqueue the script
Hope this helps anyone, again, I am not sure if this is the best way to do it, but upon examining WooCommerce source, it seems WooCommerce
doesn't provide a convenient hook to accomplish this task with ease (at least not yet)
If you have a better approach than this please share.

Protect wordpress theme with license key validation

I'm planning to develop some professional Wordpress Themes and would like to protect it using license keys, is it possible?
If so, would any one be willing to link to some posts or articles to help me get started?
You could set up a database on your own server, holding the license key and the licensed url for the theme. Then, set up an admin page for your theme. Within, first register a license settings array. Then implement a hidden settings field on that same page that gets updated whenever the license key is being updated by site admin. the update function sends a request to your server passing the license key and the $_SERVER's host and setting the hidden license_settings field to either true or false.
A really simplified code would look like this:
functions.php
<?php
// functions.php
require("myadminpage.php");
# Functions follow here...
?>
myadminpage.php
<?php
// myadminpage.php
// register settings
function my_settings_init() {
register_setting('settings_license', 'settings_license');
}
// register admin page
function my_add_admin_page() {
add_menu_page(__( '' ), __( 'Manage License' ), 'administrator', 'myadminpage', 'my_admin_page');
}
add_action('admin_init', 'my_settings_init');
add_action('admin_menu', 'my_add_admin_page' );
if(isset($_GET["settings-updated"]) && $_GET["settings-updated"] == true) {
$options = get_option('settings_license');
$key = $options["key"];
$host = parse_url($GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI'], PHP_URL_HOST);
$url = sprintf("http://you.com/check-license.php?key=%s&url=%s", $key, $host);
$options["valid"] = trim(file_get_contents($url)) == 1) ? "true" : "false";
update_option('settings_license', $options);
}
// callback function that renders your admin page
function my_admin_page() {
settings_fields('settings_license');
$options = get_option('settings_license');
?>
<form method="post" action="options.php">
<input id="settings_license[key]" type="text" name="settings_license[key]" value="<?php echo $options["key"]; ?>">
<input id="settings_license[valid]" type="hidden" name="settings_license[valid]" value="<?php echo $options["valid"]; ?>">
<input type="submit" value="Save">
</form>
<?php
}
?>
Now you can, when ever you need/want, get the license options and handle the invalid usage in any way you want. Eg (a rude way):
header.php
<?php
// very first line
$license = get_option('settings_license');
// see: http://ckon.wordpress.com/2006/08/09/server-request_uri-doesnt-always-work-correctly-heres-how-to-fix/
$ruri = $GLOBALS['HTTP_SERVER_VARS']['REQUEST_URI'];
if(!preg_match("#wp-admin#", $ruri) && $license["valid"] != "true") {
wp_die( __('This website uses unlicensed software.<br>Administrators can update their license key here.') );
}
# rest of header.php comes here..
Finally obfuscate your php code (eg http://www.ioncube.com/sa_encoder.php) and you're done. However, make sure you're not violating any other licenses, such as WP's. If there's one single line of WordPress core functions used within your final code, you can not release it under any other license than WP, which is GPL.
I don't think so. After all, the users must have the php code to use the theme and if they have it - they may alter it in a such way that it won't need a key any more.

Programmatic Views in Drupal 7

I'm trying to create two views.
View-1 is a list of nodes.
View-2 is an image gallery associated with each node.
I basically want to pass the node title from View-1 to a programmatic View-2, so that each row in View-1 will load View-2(with a result set filtered by the title of View-1!).
I'm confused about the approach. Should this happen in a custom module, preprocess functions, or some combination thereof?
I run into this a lot - wanting to pass an argument from a primary view to a secondary view that displays with each result.
I realize that the question is a bit general, but I'm curious how folks with more experience would approach this problem.
I've done this before on D6 where basically I just create a couple template tpl.php files for my View-1.
Inside my View-1 template for Display Output (views-view--default.tpl.php in D7 now)
I would simply programmatically find the value passed or returned by View-1 for this row.
In your case on each row you would check to see which node is returned by View-1 and then I'd add code in my View-1 template to programmatically load View-2 based on the current View-1 row (ie. node in your case.)
Make sense? 5 months late on the response but I was looking for a refresher and seeing if there's a better way to do this now in D7.
UPDATE:Just did this on my new D7 install. As an example I'll explain how it relates to my Ubercart implementation.
Ubercart, when installed, has it's main "home" shop page located at mysite.com/catalog
This page, when loaded, calls a View created by Ubercart called uc_catalog_terms. It is a taxonomy based view and all it does is grab all your Catalog taxonomy categories and render them.
E.g
As a clothing store, when you navigate to mysite.com/catalog, all you'll see at this page is a grid structure like:
Sweaters Shirts Jeans
My requirement was that I needed to show the shop catalog categories/terms on this page, but ALSO show 3 random products (images) from that category/term below it each catalog category.
E.g
Sweaters
Random Sweater #1 - Random Sweater #2 - Random Sweater #3
Jeans
Random Jean #1 - Random Jean #2 - Random Jean #3
How is this accomplished?
I created my own brand new custom view (no page or lock, just default) which grabs 3 random product images based on a taxonomy term ID argument and renders 3 linked product images. I'll call this custom view random_catalog_items. If 15 is the term ID for Sweaters, when this view is called with the argument 15 it will only render 3 random linked sweater product images.
I now went back to uc_catalog_terms view and created a views-view-fields--uc-catalog-terms.tpl.php (Row Style Output) template file.
THE DEFAULT VIEW VERSION OF THIS FILE (BEFORE MODIFICATION) IS:
<?php foreach ($fields as $id => $field): ?>
<?php if (!empty($field->separator)): ?>
<?php print $field->separator; ?>
<?php endif; ?>
<?php print $field->wrapper_prefix; ?>
<?php print $field->label_html; ?>
<?php print $field->content; ?>
<?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>
THE MODIFIED VERSION BECOMES:
<?php foreach ($fields as $id => $field): ?>
<?php if (!empty($field->separator)): ?>
<?php print $field->separator; ?>
<?php endif; ?>
<?php print $field->wrapper_prefix; ?>
<?php print $field->label_html; ?>
<?php
$title = str_replace('/','-',strtolower($field->raw));
print '<img src="'.drupal_get_path('theme','my_theme').'/images/catalog/'.$title.'-header.png" />';
print '<hr style="width: 100%; background: #000; height: 2px; margin-top: 3px;"/>';
// get the taxonomy term ID
$tid = $row->tid;
// render the 3 random items
if ($random_products = views_get_view('random_catalog_items' )) {
print $random_products->execute_display('default', array($tid));
}
?>
<?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>
So as you can see inside the first View, for every row that is rendered I get the current taxonomy term ID being shown through the available row result object - $row->tid and then I simply call my created view for each row, passing along this Term ID as the argument for it. I leave a lot of the default code in there but inside my view configurations the LABELS and such are set to HIDDEN so they don't even render anyway.
In your case it should be very easily adaptable to just pass a Node NID instead of a Taxonomy Term ID.
VOILA IT ALL WORKS! View within a View! Hope this helps :)
It helps to have the Devel module loaded since then inside these View templates you can debug and see what variables are available to you via something like print krumo($row).
Personally I would avoid views here alltogether.
A simple module using a hook_menu to define the menu-items and two simple menu-callback-functions dealing with the required parameters.
The alternative would be to make all the custom parameters and custom query-filtering and tables known to views.
My (pseronal) rule of thumb is:
If you are certain you will re-use the code several times in future projects a view-addon is worth the investment.
If you will use the views-interface for more then one-time-setup (the general use) e.g. define or change views in an editors/webmasters workflow this makes sense.
The basics of this is really simple and most probably a lot less coding and development then writing the views extensions.
/** Implementation of hook_menu().
*/
function gallery_menu() {
$items = array();
$items['gallery'] = array(
'title' => 'Gallery',
'page callback' => '_gallery_list',
'access arguments' => array('access content'),
);
$items['gallery/%gallery'] = array(
'title' => 'For dynamic titles, see title_callback documentation',
'page callback' => '_gallery_view',
'access arguments' => array('access content'),
);
return $items;
}
/** Load a gallery from database. Name follows %parameter_load hook.
*/
function gallery_load($id) {
return db_query("SELECT * FROM {galleries} WHERE id = %d", $id);
}
/** Render a list of galleries.
*/
function _gallery_list() {
$html = "";
$galleries = pager_query("SELECT * FROM {galleries}", 10);
foreach($galleries as $gallery) {
$html .= check_plain($gallery->title); //You would actually build vars here and push them to theme layer instead.
}
$html .= theme("pager");
return $html;
}
/** Load a gallery from database. Name follows %parameter_load hook.
*/
function gallery_load($id) {
return db_query("SELECT * FROM {galleries} WHERE id = %d", $id);
}
/** Render a list of galleries.
*/
function _gallery_view($gallery) {
$html = "";
$images = pager_query("SELECT * FROM {images} WHERE gallery_id = %d", 10, $gallery->id);
foreach($images as $image) {
$html .= check_plain($image->title); //You would actually build vars here and push them to theme layer instead.
}
$html .= theme("pager");
return $html;
}
Obviously, as stated in the comments, you would additionally create a few theme functions to handle the rendering, to 1) avoid hardcoded spagetty-HTML all over your module and b) allow the frontenders to stay in their theme when creating the HTML.
This sounds like a good opportunity to use an ajax callback. You could have your primary view on a part of the page just like normal and a secondary view in a custom block or something. when focus lands on the primary item (in the form of a button click or hover or something) you can use an ajax callback to replace the content of your custom block with the secondary view using your argument.
are you using drupal 6 or 7 for this? my understanding is that they do this is different ways.

Wordpress : Add a custom field directly above the title input field (w/o modifiying core files)?

Does anyone know of a way to add an input field (or any type of html for the matter) directly above (or below) the title input field on the post edit page ?
I'm looking of a way to do this without modifying core files (I'm doing this as part of a plug-in which creates a custom post-type).
I'm not aware of any available wp hooks in that area of the edit-form-advanced.php file which could help out. I really hope some has come up with a genius workaround !
Since version 3.5 wordpress introduced new hooks for the add/edit post screen called edit_form_after_title and edit_form_after_editor. So now i think we can easily add new html element after wordpress input title and input content.
just use filter like this on your functions.php
add_action( 'edit_form_after_title', 'my_new_elem_after_title' );
function my_new_elem_after_title() {
echo '<h2>Your new element after title</h2>';
}
add_action( 'edit_form_after_editor', 'my_new_elem_after_editor' );
function my_new_elem_after_editor() {
echo '<h2>Your new element after content</h2>';
}
You're on the right track; pursue the add_action('admin_head') point of entry. What you want can specifically be done with a bit of JavaScript + jQuery (which is built into WP). To display the input field above the title input field, do something like this:
add_action('admin_head', 'my_admin_head_in_posts');
function my_admin_head_in_posts() {
?>
jQuery('#post').before(
'<div id="id_my_field" class="updated below-h2">' +
'<input type="text" name="my_field" value="lol" />' +
'</div>'
);
<?php
}
And you should be seeing something like this:

How do I get a list of items in the Wordpress media library on a plugin options page?

I'm writing a Wordpress plugin which injects a grid of images just above the footer on all frontend pages. The application is to display sponsor's logos. I'd like to harness the WP Media Library since the logos are already uploaded for use on the 'sponsorship' page and in posts.
Essentially I'm stuck at accessing the media library interface on the plugin's options page. All of the legwork is done in terms of creating the options page, using the action hook to place content on frontend pages from the plugin, etc. What I need now is to be able to display all the files in the media library in a list on the options page, and provide a checkbox or something to allow the user to select certain files for insertion above the footer.
The Media Library API seems to be aimed at people writing themes or media plugins. Help understanding what to make use of would be great!
I think you'd be much better off adding your own column into the existing media library, rather than try re-coding it yourself;
function my_media_col($cols)
{
$cols['my_col'] = 'Footer';
return $cols;
}
add_filter('manage_media_columns', 'my_media_col');
function handle_my_media_col($name, $id)
{
if ($name !== 'my_col')
return false;
$in_footer = get_option('in_footer', array());
?>
<input type="checkbox" name="in_footer[]" value="<?php echo $id; ?>" <?php checked(in_array($id, $in_footer)); ?> />
<?php
}
add_action('manage_media_custom_column', 'handle_my_media_col', 10, 2);
Then just hook onto the load-upload.php (the library page) and save changes when POST'ed;
function save_my_col()
{
if (!isset($_POST['in_footer']))
return false;
$in_footer = $_POST['in_footer'];
if (is_array($in_footer))
$in_footer = array_map('absint', $in_footer); // sanitize
else
$in_footer = array();
$in_footer = array_merge(get_option('in_footer', array()), $in_footer);
$in_footer = array_unique(array_filter($in_footer));
update_option('in_footer', $in_footer);
}
add_action('load-upload.php', 'save_my_col');
Note this is just an example, and I may have one or two typos.
UPDATED:
My code example should store an array of IDs in the options table, under the key 'in_footer'.
Put in practice, you can get all media items marked 'in footer' like so;
$query = new WP_Query(array('post__in' => get_option('in_footer', array()) ));
if ($query->have_posts()): while ($query->have_posts()): $query->the_post();
?>
<?php the_title(); ?>
<?php endwhile; endif; ?>

Resources