Getting rid of Redux Framework annoyances

Redux Framework is a nice option framework for WordPress theme and plugin developers, and probably it is one of the most used frameworks out there. However, it comes with a few annoyances that many peoples are complaining of. First one is their dashboard widget. There should be a hook to remove that from my theme. Second, it asks the user to opt-in for tracking usage info. Third, it shows unnecessary admin notices when you’re developing in localhost. These admin notices doesn’t display in production server. But it still annoys me while in development mode because it has no effect on dev_mode value set to true or false. It also adds an extra “Redux Framework” sub menu page under Tools menu which was meant for support options but is not needed when you’re a theme developer and providing support by yourself.

Screen Shot 2015-04-24 at 9.59.11 PM

So here is how you can get rid of these things. Remember, there are no hooks to turn them off easily and you need to modify core files. Fortunately the changes are simple. Let’s do it!

1. Turn off Dashboard Widget and Stop admin notices

Open ReduxCore/framework.php and you will find the following code block around line # 405 (depending on your version of Redux Framework)

if ( $this->args['dev_mode'] == true || Redux_Helpers::isLocalHost() == true ) {
    include_once 'core/dashboard.php';

    if ( ! isset ( $GLOBALS['redux_notice_check'] ) ) {
        include_once 'core/newsflash.php';

        $params = array(
            'dir_name'    => 'notice',
            'server_file' => 'http://www.reduxframework.com/' . 'wp-content/uploads/redux/redux_notice.json',
            'interval'    => 3,
            'cookie_id'   => 'redux_blast',
        );

        new reduxNewsflash( $this, $params );
        $GLOBALS['redux_notice_check'] = 1;
    }
}

Comment out the whole block and you’re done!

2. Turn off opt-in Tracking popup

This one is quite easy. Just add the disable_tracking in your option setting arguments (where you define your opt_name value) and you’re done

$args = array(
    // TYPICAL -> Change these values as you need/desire
    'opt_name'             => $opt_name,
    'disable_tracking' => true,
    ...

3. Remove “Redux Framework” sub menu under Tools

To remove that menu, add the following code-block in your functions.php. Remember to set the priority higher than 10 :)

/** remove redux menu under the tools **/
add_action( 'admin_menu', 'remove_redux_menu',12 );
function remove_redux_menu() {
	remove_submenu_page('tools.php','redux-about');
}

Hope you liked this article. Enjoy!

Working with combined expressions in WHERE clauses in Laravel 4

laravel-combined

When retrieving records from tables in our database, you often have to write combined expressions in WHERE clauses like

SELECT * FROM users WHERE status=1 AND (fname = 'John' OR lname='Doe')

The query above is pulling out all users who’s status is set to 1, and fname is equal to ‘John’ or status is 1 and lname is equal to ‘Doe’. Now this query is significantly different from the following one.

SELECT * FROM users WHERE status=1 AND fname = 'John' OR lname='Doe'

Can you tell us what can go wrong with a statement like this? Well to find out more, let’s have a look at how this query will be parsed by database engine

SELECT * FROM users WHERE (status=1 AND fname = 'John') 

OR 

SELECT * FROM users WHERE lname='Doe'

So this query will pull every record that has a status set to 1 and fname equivalent to ‘John’. Then, with the previously pulled records, it will also pull all the users who has a lname equal to ‘Doe’, but this time it will pull out all users disregarding their status. Which means that users with status = 0 or 1 or 2 will also be in the resultset. I bet that is not what you were looking for while you’re writing this query and clearly understands the difference between these two queries. So you got the point of grouping or combining logical expressions and the impact that can have in your resultset. Writing a combined logical expression is easy in SQL. But what if you’re told to do the same operation using Laravel 4’s built in ORM which is called Eloquent ORM. It’s a little tricky to do the same operation in eloquent because of this combined expression, and it needs an anonymous function :) Let’s have a look at the following code in our User model

static function searchByName($fname, $lname){
    return User::where("status", 1)
        ->where(function ($query) use ($fname, $lname) {
            $query->where("fname", '=', $fname)
                ->orwhere("lname", '=', $lname);
        })
        ->get(['*']);
}

Now searchByName(…) function will work as we expected. You can try the following one and see the difference and notice how it is VERY MUCH different from our expectation

static function searchByName($fname, $lname)
{
    return User::where("status", 1)
        ->where("fname", '=', $fname)
        ->orWhere("lname", '=', $lname)
        ->get(['*']);
}

Eloquent ORM’s where function can make use of callbacks in this way. Please note how we used anonymous function as callback that also uses $fname and $lname from the arguments. That’s mainly it. I hope that you’ve enjoyed this article :)

Picking up random elements from DOM using jQuery

tumblr_n1zv0cTukw1tubinno1_1280

Selecting a group of DOM elements is super duper easy these days using CSS selectors, or a particular element via their ID. But what about picking up a random element from these group of elements? In this article I am going to show you how to do it by extending jQuery

Let’s consider that we have the following markup. Now we will pick a random button and change it’s value

<div class="container">
    <button>1</button>
    <button>2</button>
    <button>3</button>
    <button>4</button>
    <button>5</button>
</div>

Let’s extend jQuery and add a random() function to it

$.fn.random = function() {
    return this.eq(Math.floor(Math.random() * this.length));
}

Now we can pick up a random button and change it’s value quite easily.

$(".container button").random().html("Click Me");

That was easy, eh? Hope you’ll like it.

Delegating Events Instead of Direct Binding in DOM

tumblr_n1rr53o21A1tubinno1_1280

When it comes to attaching event listeners, be it a particular element in the DOM, or a group of elements via CSS selectors, most of us bind the event listener directly to the elements. Direct binding is fine when you’re doing for a PARTICULAR element, but it may create problems for a group of elements if you’re not taking extra care while event binding. To understand the issue, let’s have a look at the following code block (Here’s a live example)

 
<!-- index.html -->
<div class="container" style="margin-bottom:50px;"></div>
<input type="button" value="Add More Buttons"  id="addmore" />

And we added the following javascript (depends on jQuery)

 
;(function($){
    $(document).ready(function(){
      $("#addmore").on("click",function(){
        
        var l = $(".container button").length+1;
        $("<button/>").html("Click Me "+l).appendTo($(".container"));
        $(".container button").on("click",function(){
          alert("Clicked");
        });
        
      });
    });
})(jQuery);

Now if you add more and more buttons, you can see that it repeatedly attaching events. See the effect in the following animation

dom-1

To avoid these repeated bindings, you can modify your code like this and detach all the event listeners which were attached previously to these buttons.

$(".container button").off("click");
$(".container button").on("click",function(){
  alert("Clicked");
});

This is boring, lengthy and sometime risky because you have to manually detach events everytime a new DOM element which satisfies your CSS selector rule adds in the container. And if you forgot to do that, chances are higher to break something somewhere.

Now, to save from this pain, jQuery had introduced event delegation which doesn’t bind the event listener to the dom elements but it delegates the event from their parent. This way, you will never have to worry about detaching previous attached event listeners anymore. Let’s have a look at our final code block, and here is a live example too

;(function($){
    $(document).ready(function(){
       
      //event delegation
      $(".container").on("click","button",function(){
          alert("Clicked");
      });
      
      $("#addmore").on("click",function(){
        
        var l = $(".container button").length+1;
        $("<button/>").html("Click Me "+l).appendTo($(".container"));
        
      });
    });
})(jQuery);

In the above example see how we have delegated the click event to every “button” in the container div. Once the delegation is done, it doesn’t matter whenever a new dom element (in this case, a “button”) inserts in the container. It will always capture the “click” event because the parent div “.container” will delegate that event to it properly. All you have to do is select a parent element, and then delegate the event to childrens (via CSS selector) belonging to it. It’s the same .on() method, just takes an extra parameter in the middle which represents the CSS selector to which the event will be delegated.

//event delegation
$(".container").on("click","button",function(){
  alert("Clicked");
});

By using event delegation in jQuery for a group of DOM elements, you can avoid risks, keep your code cleaner and save yourself from some overkill every time. Hope you’ve liked this article :)

How to enable some useful text formatting options in TinyMCE in WordPress

tumblr_na06t4fnlI1tubinno1_1280

Most of the time default TinyMCE editor in WordPress is pretty adequate for everyday text formatting. However, there are a lot of extra formatting options which are hidden out of the box. Enabling these options will give you extra formatting features that will be useful for many of us. In this article, I will show you how to enable these hidden formatting options in TinyMCE. Just add the following code block in your theme’s functions.php file

function tinymce_enable_more_buttons($buttons)
{
    $buttons[1] = 'fontselect';
    $buttons[2] = 'fontsizeselect';
    $buttons[3] = 'styleselect';
    return $buttons;
}

add_filter("mce_buttons_3", "tinymce_enable_more_buttons");

Now you can see these extra options in the editor as shown in the animation below.

format

Hope you liked this article.

Find n number of posts randomly from a group of categories in WordPress

tumblr_n2hutxfrNr1tubinno1_1280

When you are developing a theme, or maybe writing a plugin, it is often required to display related posts in single posts page. These related posts are fetched by various criteria. Sometimes they are fetched from the same categories a post belongs to, or by tags. Sometimes they are set by the author of the posts.

In this article I am going to show you how to fetch the categories of a particular post, and then fetch some random posts from these categories. It’s not as tough as you’re thinking.

Fetch the categories of a post
You can quickly fetch the categories assigned to a particular post using get_the_category() function. Let’s have a look at the following code block

$post_id = 1234;
$categories = array();
$_categories = get_the_category($post_id);
foreach ($_categories as $_cat) {
    $categories[] = $_cat->term_id;
}

Now you have the array of category ids which are assigned to a particular post with post id “1234”.

Fetch posts from these same categories
Now we are going to fetch some posts from these categories fetched in step 1. We will use kinda less documented category__in and post__not_in parameters with get_posts() function. We will make sure that the post “1234” doesn’t come in the list of random posts. Because it will be silly to display that same post as a relative.

$args = array(
        'orderby' => 'rand', //important to fetch random posts
        'post_type' => 'post',
        'numberposts' => 3,
        'post__not_in' => array($post_id), //exclude the same post
        'category__in' => $categories,
        'post_status'=>'publish'
    ); 
$related_posts = get_posts($args);

Now you have an array of 3 related posts, which are related to the post “1234” by belonging in the same categories. Their properties are described in details here in this Codex Article

That was easy, wasn’t it? Hopefully you will find it useful in your next WordPress theme project. Good night.

Passing data from PHP to the enqueued scripts in WordPress

tumblr_nau9zqjZay1tubinno1_1280

Enqueueing scripts, while being as one of the most common tasks for WordPress theme and plugin developers, has a very nice companion feature that can be used to pass data to it. These data will then be available in the native scope of those scripts. In this short article, I am going to show you how to to this

Remember the first parameter of wp_enqueue_script() function? It’s called ‘handle’, and works as a reference point. We need this handle to send some data to it with the help of wp_localize_script() function. Let’s have a look at the following example.

add_action("wp_enqueue_scripts","my_scripts_loader");
 
function my_scripts_loader(){
    $data = array("home"=>site_url());

    wp_enqueue_script("myscript","path/to/my/script.js");
    wp_localize_script( "myscript", "blog", $data );

}

wp_localize_script() takes the handle of the script file, a variable name and an array. Finally, wp_localize_script converts that array into a JSON object and makes available in the local scope of that javascript file via that variable name. So, from the example above you can write the following code in your script.js and it will show you your blog URL, which was actually passed to it using wp_localize_script function

alert(blog.home);

This feature is pretty handy for developing themes and plugins, to pass data from your PHP scripts to the external javascript files. Hope you’ve enjoyed this article.