How to create a wordpress widget based on post settings - wordpress

I would like to create a WordPress plugin/widget that I can add to my post either through the Visual Composer area (widget should be selectable) or simply as a shortcode.
The functionality of this widget is that it should allow me to take the settings of that post as an argument in the main function so that I can change the output of the widget based on what is selected for the post.
For example, I have categories for all my posts and if I have a certain category selected, I want to change the output of the widget based on that.
Does anyone know of a good boilerplate to get me started with this?
Thanks

You can create your own widget using the Widget API or the Shortcode API for shortcodes.
Since you want to change the content shown in your, for instance, widget, based on the current post, in the widget() method (which is the method that prints your widget's content in the frontend) you can add your conditionals or whatever you want to print there.
The $post is available in your widget, so you can use functions like get_post_meta() to retrieve the post's settings if you use custom fields, or any other function like get_the_ID() or has_category().
For example:
/**
* Outputs the content of the widget
*
* #param array $args
* #param array $instance
*/
public function widget( $args, $instance ) {
if ( has_category( 'books' ) ) {
echo 'Hey!, I have the Books category!';
} else {
echo "Hey... I don't.";
}
}

Related

WP: overriding recent post widget class

I want to customise the "recent posts" widget.
Since it's not good to edit the core for different reasons, I read about working it in functions.php extending WP_Widget with a new class and overriding the widget($args, $instance) function editing the code I want to customise, next to add it to the widget_init hook but I can't get how it works.
I mean, I think I should extend the WP_Widget_Recent_Posts then tell WP to use my class instead of the original one but....how can I do it?
Thanks
It looks like you can get away just by using the dynamic_sidebar_params() filter along with a search/replace.
add_filter( 'dynamic_sidebar_params', 'replace_widget_class' );
function replace_widget_class( $params ) {
if ( $params[0]['widget_name'] == 'Recent Posts' ) {
$params[0]['before_widget'] = str_replace( 'widget_recent_entries', 'widget_recent_entries_NEW', $params[0]['before_widget'] );
}
return $params;
}

what is difference between action hook and filter hook in wordpress?

I read the action hook is use for call the functions and filter hook is use for filtering the content before save or display on website. Can you tell me the some working phases of project example where we use action and filter hook. So it will better to understand more.
Action: Doing new things. Ex. adding CSS and JS.
Filter: Doing something which is already in WordPress. Adding or removing some things. Assume adding some text after post content. It means doing something with WordPress.
Example code:
add_action('admin_menu','my_func',8,2);
function my_func($one, $two){
//Something here …
}
In short:
Filter Hook: used to modify (filter) a value
Action Hook: do something, right at this moment
Filter Hook Example:
$name = "Smith";
$gender = "female";
echo apply_filter('form_of_address', $name, $gender );
// somewhere else
add_filter( 'form_of_address', function( $name, $gender ) {
if ( "female" == $gender ) {
$name = "Mrs. " . $name;
} else if ( "male" == $gender ) {
$name = "Mr. " . $name;
}
return $name
}, 10, 2 );
You want to know what the difference is between an action and filter event (hook).
Let's start with understanding what a hook or event is in WordPress.
What is a Hook (Event)?
Through the Plugin API, WordPress provides us with the means to run our code when events happen.
Programs run in a specific order from top to bottom. Line 1 runs and then line 2 and so on. As WordPress loads in files, each of those run and so on.
As the web page request is processed, WordPress Core is running the lines of code and doing stuff. But what if you need to run your code at a certain point in the request cycle? For example, let's say you want to change the post's byline from the default of the theme. Using a filter event (hook), you gain:
access to the actual value or HTML before it's sent out to the browser
the ability to change that value or HTML
the ability to run other code at a specific point in the web page request cycle.
Why are there hooks (events)?
WordPress runs out of the box without our custom themes or plugins. But the Plugin API gives you and I as well as all developers the means to customize, change the default behavior, and extend WordPress.
It lets us run our code when we need to, i.e. at specific points in the web page request cycle.
Pre-registration
For our code to run, we need to pre-register our callback, which is the function or method that we want to run at that specific point. You use add_action() to pre-register an action event callback. You use add_filter() to pre-register a filter event callback.
When you pre-register your callback, it's being added into a registration lookup table, which is an array.
Then when the event fires, your callback and all the others are called in order. You set the order using the priority parameter. The argument(s) are passed to your callback. Then your method or function runs.
Here's a video that explains the big picture of this process and the why of it.
Action vs. Filter
A filter event (hook) allows you to filter the return value. It gives you (and all the other registered callbacks) the ability to filter, which means change the value.
Think about that. Let's say you want to change the "read more" link. Maybe you want it to say "Continue reading" and maybe you want it to be a button instead of a just a hyperlink. The filter allows you:
to receive the current value
change it to what you want
send it back by returning it
That new value is then passed along to all the other registered callbacks and then eventually returned to the line of code that fired the event.
Action Event
The action event (hook) is the same as a filter except that the value is not returned.
The event is fired, such as init or plugins_loaded. The pre-registered callbacks are called in order and any arguments are passed to each one. Your function or method is called. You can run your code.
It gives you the means to do something at a specific point in the web page request cycle.
Wrap it Up
Think about the power of the event management system. If you need to run something say right after all of the plugins have loaded, you pre-register to the plugins_loaded event name. When Core fires the event by doing do_action( 'plugins_loaded' );, your code will run too.
Filter and Action events (hooks) let you run your code at a specific point in the web page request cycle.
The Difference
Filter events (hooks) let you filter or change the value before it's processed. Action events do not let filter.
How do you fire an event?
For action events, you can use do_action( 'event_name' ) or do_action_ref_array( 'event_name', $args ).
For filter events, you can use apply_filters( 'event_name', $value_to_filter ) or apply_filters( 'event_name', $args );
Examples
Let's say you want to add a styling class attribute to the post. You can pre-register to the post_class event name. You'll receive an array of classes.
add_filter( 'post_class', 'add_my_class_attribute_to_post_class' );
/**
* Add styling class to the post class.
*
* #since 1.0.0
*
* #param array $classes
*
* #return array
*/
function add_my_class_attribute_to_post_class( array $classes ) {
$classes[] = 'some-class-attribute';
return $classes;
}
What if you wanted to add a styling class to the front page's body.
add_filter( 'body_class', 'add_front_page_to_body_class' );
/**
* Add the class attribute "front-page" to the body classes.
*
* #since 1.0.0
*
* #param array $classes
*
* #return array
*/
function add_front_page_to_body_class( array $classes ) {
$classes[] = 'front-page';
return $classes;
}
Notice how you're changing the value and then returning it back.

View composers or similar for Wordpress's Timber template library?

Is there an option or way to provide data to all instances or rendered pages when using the Timber library?
I would like to set some site wide data within the core functions.php file and have it be available to all templates without the need to manually add it before every Timber::render()
I’d use the timber_context filter (or timber\context) to add your own data when you use get_context.
Here’s an example for how to add a menu/navigation (from the Wiki page on TimberMenu):
add_filter( 'timber_context', function( $context ) {
/* So here you are adding data to Timber's context object, i.e... */
$context['foo'] = 'I am some other typical value set in your functions.php file, unrelated to the menu';
/* Now, in similar fashion, you add a Timber menu and send it along to the context. */
$context['menu'] = new Timber\Menu(); // This is where you can also send a WordPress menu slug or ID
return $context;
} );
The minimum you have to do to get your data into your template will then be:
$context = Timber::get_context();
Timber::render( 'template.twig', $context );

Can I hide a Category (and its subcategories) from the sidebar?

I put the widget category on the primary sidebar, from the dashboard. Than, on code, I use :
<?php get_sidebar('left'); ?>
and it create the code for the categories. Now, I'd like to hide the category with tag_ID=6, and all of its subcategories.
How can I do it?
Tried this tutorial, but seems that I don't have the $cat_args = "orderby=name&show_count={$c}&hierarchical={$h}"; line? I'm on last version of WordPress, 3.4.2
The tutorial seems outdated, so I wouldn't rely on that. It is not necessary to hack around in the WordPress-source - create a simple Plugin which hooks into the right filters.
In your case those filters are widget_categories_dropdown_args (when you select "Display as dropdown" in the Widget-options) and widget_categories_args (if the Widgets displays the list as normal text with links).
With that knowledge you can now code the actual plugin (I've called it Myplugin, I think you should rename it) - just put that PHP code into the file wp-content/plugins/myplugin.php:
<?php
/**
* #package Myplugin
* #version 1.0
*/
/*
Plugin Name: Myplugin
Plugin URI: http://example.com
Description:
Author: You
Version: 1.0
Author URI: http://example.com
*/
// Create a list with the ID's of all children for
// the given category-id
function myplugin_recursive_filter($catid) {
$result = array($catid);
$cats = get_categories(array(
'child_of' => $catid,
));
foreach($cats as $category) {
$result[] = $category->cat_ID;
}
return implode(",", $result);
}
// Actual filter function. Just set the "exclude"
// entry to a comma separated list of category ID's
// to hide.
function myplugin_filter_categories_args($args) {
// 6 is the "tag_ID"
$args['exclude'] = myplugin_recursive_filter(6);
// or hard code the list like that:
//$args['exclude'] = '6,10,11,12';
// but you'd have to include the ID's of the
// children, because "eclude" is not recursive.
return $args;
}
// Register the filter to the relevant tags
add_filter('widget_categories_dropdown_args',
'myplugin_filter_categories_args', 10, 1);
add_filter('widget_categories_args',
'myplugin_filter_categories_args', 10, 1);
The function myplugin_recursive_filter is necessary, because the exclude-entry is not recursive (except if you check "Show hierarchy" in the widget options). If your categories don't change that much you could replace function call with a hard-coded list of ID's (with the children) for better performance.

is there a way (plugin) to insert html/css/images ect automatically into every wordpress post?

is there a way (plugin) to insert html/css/images ect.. automatically into every wordpress post? most of my posts are going to be very similar so is there a plugin that will automatically insert the pre written html/css/ ect in every post as opposed to me entering it manually every time.
Thank you in advance ;-)
You can write your own simple function for this, see my example below:
add_filter( 'default_content', 'my_editor_content' );
function my_editor_content( $content ) {
global $post_type;
if( $post_type == 'post') { /* Or your custom post type, pages etc. */
$content = 'Your custom HTML/CSS content here';
}
return $content;
}
Place this in functions.php and it will be the default content of every new post/page/custom post type you create.
For a list of available post types, please refer to the Codex
You could use a plugin such as Ad injection, it will allow you to do what you need without having to alter / amend / ad any code to the templates or files

Resources