4elements, Amsterdam, Holland

  1. 50 Filters of WordPress: Filters 41-50

    In the previous parts of this series, we went through 40 WordPress filters. In this tutorial, we're going to see the last 10 filters and do examples with each.

    Let's begin!

    Filtering the Script Loader Source

    WordPress has its own script loader, wp_enqueue_script(), which allows us to "queue" JavaScript files and not hard-code them. And this little filter called script_loader_src lets us how the scripts will be queued and outputted.

    Example: Remove the Version Parameter from Scripts

    Google Page Speed, Yahoo YSlow and other website performance measurement tools usually hate URL parameters in JavaScript files. And they're right, too: Scripts with parameters at the end of their URLs don't get cached by "proxy servers" (more info on this topic here) and sadly, WordPress enables "version" parameters for scripts (and styles, too) by default. Luckily, we can simply remove those ver parameters with a few lines of code:

    <?php
    
    function script_loader_src_example( $src ) {
    	return remove_query_arg( 'ver', $src );
    }
    
    add_filter( 'script_loader_src', 'script_loader_src_example' );
    // Tiny bonus: You can do it with styles, too!
    add_filter( 'style_loader_src', 'script_loader_src_example' );
    
    // Example source: http://www.wpmayor.com/15-practical-ways-boost-wordpress-speed/
    
    ?>

    Done! Your JavaScript (and CSS) files will not have any version parameters anymore.

    If you want to learn more about proper JavaScript usage with WordPress, be sure to check out my article on this topic.

    Adding HTML to the "Featured Image" metabox

    The admin_post_thumbnail_html filter, as its name suggests, allows you to add HTML content inside the "Featured Image" metabox. The HTML will appear right below the "Set featured image" link.

    Example: How to Help Your Client Set Featured Images Correctly

    Imagine that you're making a personal blog for your client, but he insisted on maintaining the blog on his own instead of hiring an assistant. He always forgets how to add a featured image (He calls it "top image".) and you need to leave a reminder on the New Post page. Here's how you do it:

    <?php
    
    add_filter( 'admin_post_thumbnail_html', 'admin_post_thumbnail_html_example' );
    
    function admin_post_thumbnail_html_example( $html ) {
    	return $html .= '<p>Hi Mr. Smith! Click above to add an image to be displayed at the top of your post. Remember: <strong>The width of the image should be at least 900px</strong>!</p>';
    
    }
    
    ?>

    With your helpful reminder, your client will never forget to set a "top image" with a minimum width of 900 pixels.

    Controlling Comment Flooding Attacks - comment_flood_filter

    By default, WordPress prevents "comment flooders" who repeatedly comments on your posts. For example, if a visitor posts a comment to a post in your website, they must wait 15 seconds (default value) before posting another comment. This filter lets you change the time setting to another value – or disable flood checking altogether.

    Example: Making Commenters Wait Longer

    As I said, WordPress makes visitors wait for 15 seconds before posting another comment. In some scenarios, you might need to increase this time limit to, say, 60 seconds. Here's how you do it:

    <?php
    
    add_filter( 'comment_flood_filter', 'comment_flood_filter_example', 10, 3 );
    
    function comment_flood_filter_example( $flood_control, $time_last, $time_new ) {
    	$seconds = 60;
    	if ( ( $time_new - $time_last ) < $seconds )
    		return true;
    	return false;
    }
    
    // Example source: http://codex.wordpress.org/FAQ_Working_with_WordPress#How_do_I_prevent_comment_flooding.3F
    
    ?>

    Change the value "60" above to anything you want.

    Bonus Example: Disabling Comment Flood Checking

    If you don't care about visitors speed-commenting, you can disable checking for flooding by using the two simple lines below:

    <?php
    
    remove_all_filters( 'comment_flood_filter' );
    add_filter( 'comment_flood_filter', '__return_false', 10, 3 );
    
    ?>

    Notice the remove_all_filters() function? As its name suggests, it removes all filtering functions from a filter hook.

    Changing the Items at the "At a Glance" Section 

    The "At a Glance" section (formerly named "Right Now") keeps us up to date about how many posts, pages and comments are there in the database of your website. The dashboard_glance_items filter helps us show additional information there, like the number of posts of a custom post type.

    Example: Showing Your "Events" Post Type at the "At a Glance" Section

    Let's imagine that you have an "event blog" where you keep your visitors informed by new local events which you post as a custom post type named "Events" (and with the id event). To be able to see the count of events in your blog, you can use the function below and hook it to the dashboard_glance_items filter like so:

    <?php
    
    add_filter( 'dashboard_glance_items', 'dashboard_glance_items_example' );
    
    function dashboard_glance_items_example( $items = array() ) {
    	$post_types = array( 'event' );
    	foreach( $post_types as $type ) {
    		if( ! post_type_exists( $type ) ) continue;
    		$num_posts = wp_count_posts( $type );
    		if( $num_posts ) {
    			$published = intval( $num_posts->publish );
    			$post_type = get_post_type_object( $type );
    			$text = _n( '%s ' . $post_type->labels->singular_name, '%s ' . $post_type->labels->name, $published, 'your_textdomain' );
    			$text = sprintf( $text, number_format_i18n( $published ) );
    			if ( current_user_can( $post_type->cap->edit_posts ) ) {
    			$output = '<a href="edit.php?post_type=' . $post_type->name . '">' . $text . '</a>';
    				echo '<li class="post-count ' . $post_type->name . '-count">' . $output . '</li>';
    			} else {
    			$output = '<span>' . $text . '</span>';
    				echo '<li class="post-count ' . $post_type->name . '-count">' . $output . '</li>';
    			}
    		}
    	}
    	return $items;
    }
    
    // Example source: http://www.trickspanda.com/2014/03/add-custom-post-types-glance-dashboard-widget-wordpress/
    
    ?>

    Easy, right? Change the value of the $post_types variable (array) to suit your needs.

    Changing the Default Login Form Messages

    The login_message filter allows us to edit default messages that's outputted right above the login forms of our WordPress installations. (Not "errors", just neutral messages.)

    Example: Changing the Default "Lost Password" Messages

    If you ever need to simplify the default "lost password" instructions ("Please enter your username or email address. You will receive a link to create a new password via email."), you can change it like so:

    <?php
    
    add_filter( 'login_message', 'login_message_example' );
    
    function login_message_example( $message ) {
    	$action = $_REQUEST['action'];
    	if( $action == 'lostpassword' ) {
    		$message = '<p class="message">Enter your email address, then check your inbox for the "reset password" link!</p>';
    		return $message;
    	}
    	return;
    }
    
    // Example source: http://www.pypelineweb.com/blog/change-wordpress-login-message-filter-it-out/
    
    ?>

    There are a number of actions that can be found in the wp-login.php file:

    • logout
    • lostpassword and retreivepassword (alias)
    • resetpass and rp (alias)
    • register
    • login

    Just like the one we did in the example, you can write different messages for different action.

    Changing Bulk Update Messages

    There are messages displayed when you update, trash, untrash, or delete posts. If you want to edit those messages, the bulk_post_updated_messages is your guy.

    Example: Editing Custom Messages for a Custom Post Type

    Let's say you don't like the way those messages are displayed for bulk actions of your custom post type "event" and you want to change them. Here's how you do it:

    <?php
    
    add_filter( 'bulk_post_updated_messages', 'bulk_post_updated_messages_example', 10, 2 );
    
    function bulk_post_updated_messages_example( $bulk_messages, $bulk_counts ) {
    	$bulk_messages['event'] = array(
    		'updated'   => _n( '%s event updated.', '%s events updated.', $bulk_counts['updated'] ),
    		'locked'	=> _n( '%s event not updated, somebody is editing it.', '%s events not updated, somebody is editing them.', $bulk_counts['locked'] ),
    		'deleted'   => _n( '%s event permanently deleted.', '%s events permanently deleted.', $bulk_counts['deleted'] ),
    		'trashed'   => _n( '%s event moved to the Trash.', '%s events moved to the Trash.', $bulk_counts['trashed'] ),
    		'untrashed' => _n( '%s event restored from the Trash.', '%s events restored from the Trash.', $bulk_counts['untrashed'] ),
    	);
    
    	return $bulk_messages;
    }
    
    // Example source: http://codex.wordpress.org/Plugin_API/Filter_Reference/bulk_post_updated_messages
    
    ?>

    Easy, right? Remember to make the strings translatable if you're not the only one to use the plugin or theme.

    Filtering the Default Categories Widget

    In some cases, you may need to tamper with the core Categories widget. With the widget_categories_args filter, you can do that.

    Example: Excluding Categories From the Widget

    If you ever need to "hide" some categories in the Categories widget, use this code snippet:

    <?php
    
    add_filter( 'widget_categories_args', 'widget_categories_args_example' );
    
    function widget_categories_args_example( $cat_args ) {
    	$exclude_arr = array( 4, 10 );
    
    	if( isset( $cat_args['exclude'] ) && !empty( $cat_args['exclude'] ) )
    		$exclude_arr = array_unique( array_merge( explode( ',', $cat_args['exclude'] ), $exclude_arr ) );
    	$cat_args['exclude'] = implode( ',', $exclude_arr );
    	return $cat_args;
    }
    
    // Example source: http://codex.wordpress.org/Plugin_API/Filter_Reference/widget_categories_args
    
    ?>

    Change the $exclude_arr array items with the IDs of your "unwanted" categories and you're good to go.

    Redirecting the User Upon Successful Registration

    By default, WordPress just reminds you to check your email after registration and doesn't redirect you anywhere. With the registration_redirect filter, however, you can set a custom safe address to redirect upon successful registrations.

    Example: Letting New Users Download Your Awesome E-book

    If you offer a free e-book to your visitors if they sign up for your website, you can redirect them to the page with the download link of your e-book by using this simple code snippet:

    <?php
    
    add_filter( 'registration_redirect', 'registration_redirect_example' );
    
    function registration_redirect_example() {
    	return home_url( '/your-free-ebook/' );	
    }
    
    // Example source: http://wpsnipp.com/index.php/functions-php/redirect-a-successful-registration-page/
    
    ?>

    Remember, the redirection is done with the wp_safe_redirect() function which means that you can't redirect to an external site unless you used the allowed_redirect_hosts filter to specify external and "safe" hosts. We went through that filter in the first batch of these examples, be sure to read that tutorial if you haven't yet.

    Altering Fields of the Comment Form

    WordPress has the comment_form() function for displaying the comment form, and you can change its field by using the function's arguments. If you're developing a plugin, however, you won't be able to change any parameters of the function. This little filter allows us to change the HTML code of the default form fields – or remove them.

    Example: Removing the URL Field in the Comment Form

    Let's say you, as a freelance web designer, are making a "default adjustments plugin" for all your clients and for security purposes, you want to remove the URL fields in the comment forms of all your websites. You can add a really simple function (and hook it to a filter) to make it happen:

    <?php
    
    add_filter( 'comment_form_default_fields', 'comment_form_default_fields_example' );
    
    function comment_form_default_fields_example( $fields ) {
    	unset( $fields['url'] );
    	return $fields;
    }
    
    // Example source: http://wpsnipp.com/index.php/comment/remove-unset-url-field-from-comment-form/
    
    ?>

    Paste this lines into your plugin file and you're done!

    Altering the List of Acceptable File Types

    By default, you can upload a number of file types into WordPress' Media Library – check out the full list of file types here. With the help of the upload_mime filter, you can make changes with the list of allowed file types.

    Example: Prevent Uploading GIFs

    Ah, GIFs... They were popular in 1999 and they're still popular at 2014. Did you know that one of the first memes was a GIF of a dancing baby? Those were simpler times when we created "homepages" in Yahoo! Geocities and enjoying the annoying monkey sound of ICQ every time a friend IMed us...

    Ahem, anyways... If you want to end this nonsense and stop your users to upload GIFs into your website's Media Library, you can disable GIF uploads with a simple code snippet like below:

    <?php
    
    add_filter( 'upload_mimes', 'upload_mimes_example' );
    
    function upload_mimes_example( $existing_mimes = array() ) {
    	unset( $existing_mimes['gif'] );
    	return $existing_mimes;
    }
    
    // Example source: http://codex.wordpress.org/Plugin_API/Filter_Reference/upload_mimes
    
    ?>

    Bye bye, four-second movie clips that doesn't need to be seen more than one time but keeps repeating endlessly!

    End of Part Five

    We went through the last batch of 50 filters in this article. I hope you liked and learned new things from it. In the next article, we're going to have a quick look at what we've seen and close the series. See you there!

    I want to hear your thoughts, too. What do you think about these filters? Post your comments below; and if you liked the article, don't forget to share it!

     

    0 Comments

    Leave a comment › Posted in: Daily

    1. Modern Debugging Experience: Part 2


      In part 1, we saw how to write and execute JavaScript using the DevTools. In part 2, we'll look at debugging JavaScript and adopting a workflow such that solving JavaScript errors and diagnosing problems becomes more efficient.

      Debugging JavaScript Using the DevTools

      Debugger Keyword

      You can use the debugger keyword directly in your code to invoke the debugging capabilities (if any) of the JavaScript runtime. The effect of adding the keyword debugger in your code is identical to manually setting a breakpoint via the DevTools UI. In Chrome, the debugger keyword has no effect while DevTools is closed.

      Debugger Controls

      The debugger controls provide fine grained control over the debugging flow. Use these when paused at a breakpoint to effectively navigate your way through JavaScript code. Each debugger control listed in this section corresponds to a button in the DevTools that you can select while paused at a breakpoint.

      Continue

      Leaves the current breakpoint and resume code execution as normal. This does not affect other breakpoints which have not been paused yet.

      Use Continue when the current paused breakpoint is not helpful and you want code execution to resume as normal.

      Step Over

      Step through code line-by-line (one line per click) until a function call is reached. At this point, the function call is stepped "over" and you do not step into that particular function call.

      Use Step Over when what you are trying to solve is scoped with the current function, and you have no need to look at external function calls.

      Step Into

      Similar to Step Over, except that in this case, you navigate to external function calls by going to their first line.

      Use Step Into when you are interested in line by line execution as well as any external function calls.

      Step Out

      When you step into a function, Step Out will continue to execute the rest that functions code however it is not debugged.

      Use Step Out when you have no interest in the remainder of the current function and wish to continue debugging outside it.

      The Call Stack

      The call stack is active when paused at a breakpoint. The execution path which leads to the currently paused breakpoint is shown in the call stack, the top call being the most recent.

      Each call within the stack contains:

      • function name
      • file name containing the function
      • the line of code where the function exists

      Click on any call within the stack to navigate to its point in the source code with the relevant line highlighted. To copy a stack trace to your clipboard, right-click on a call and select Copy stack trace. In the call stack context menu, you can also select Restart Frame.

      Rewriting Functions While Paused at a Breakpoint

      Consider the use case that the debugger has paused midway through a callback function triggered by a click event handler, and you are trying to debug why the retrieval of the target does not seem to be working as expected. 

      You see an attempt has been made to access the target property as part of the this keyword, but you then recall it’s a property part of the event object passed as an argument to the callback function. 

      You can rewrite the function using Live Edit to verify that your changes work, and the new JavaScript is injected into the V8 engine.

      monitorEvents

      When you are writing an event handler for an event such as scroll, you may start by using console.log to see what the passed argument (the event object) looks like. A quick tip to accomplish this is to use the monitorEvents shortcut. Paste the following code in the Console Panel and then scroll the page:

      monitorEvents(window, "resize");

      Notice that the event object is logged to the console ready for inspection.

      Debug

      When you want the debugger to pause on the first line of a function during its execution, you can do either of the following:

      • Add a breakpoint via the DevTools UI.
      • Add a debugger statement to the function.

      Another technique is to execute debug(fn) which is part of the Command Line API. The function takes the function that you wish to debug as its argument, and will break on the first line of that function's execution.

      Break on Property Access

      This technique enables you to pause the debugger when a property of an object you have interest in is accessed in any way (a read or write). To break when a property of an object is read or written to, execute the following (via the Console Panel or Snippets):

      Object.defineProperty(document.body, 'scrollTop', {
      	get: function () {
      		debugger;
      	},
      	set: function (val) {
      		debugger;
      	}
      });

      This applies a getter and setter to the scrollTop property of the document.body object. In the custom getter and setter, the debugger statement exists. You can also use Object.observe to break on property additions for a specified object:

      var watchMe = {};
      Object.observe(watchMe, function() {
        debugger;
      });

      Conditional Breakpoints Using console.log

      The debugger keyword aside, to set a breakpoint via DevTools, you can click on the line of code you wish to break at within the line gutter. This method of setting a breakpoint has extra functionality: You set a conditional breakpoint which will instruct the DevTools to pause at a breakpoint only if a certain expression evaluates to true. For example, you can set a conditional breakpoint to pause only if an error argument exists.

      To set a conditional breakpoint:

      1. Right-click within the line gutter.
      2. Select Add conditional breakpoint.
      3. Enter the expression that you want DevTools to evaluate.
      4. Press Enter.
      Add conditional breakpoint

      You can also use the conditional breakpoint technique to quickly insert a console.log statement as the expression to evaluate. Since console.log evaluates to undefined, DevTools doesn’t pause, but since the expression is still executed, you can inspect the value of variables this way.

      Using Watch Expressions

      When the debugger is paused at a breakpoint, you can bring up the Console Panel in Drawer Mode using the Escape key. The code you enter is evaluated in the same context as the point at which you are paused, meaning that variables which are scoped will be accessible to you.

      Watch expressions

      A Watch Expression is a tool to simplify the technique of regular inspection (via console.log for example) of scoped variables. Watch Expressions is a pane within the Sources Panel. You can add or remove Watch Expressions using the Plus and Minus buttons. A typical object to watch for is the this object; notice how it refers to a global window object when you are not paused at a breakpoint.

      Watch Expressions will usually update while you step through code. If it does not, however, click the Refresh button.

      Exceptions

      Consider the following script:

      function a() {
          return b();
      }
      
      function b() {
          return c();
      }
      
      function c() {
          console.trace('The Trace');
          return 42;
      }
      
      a();
      Exceptions

      There are three declared functions. Function a calls function b, then function b calls function c. The script initiates the chain with a call to function a. The console.trace statement logs to the console a stack trace from the point where the method was called. Using console.trace displays the output of using console.trace.

      Note that function names and the lines where they are called are shown in the trace message. You can click on the line number to be taken to its point in the Source Code via the Sources Panel. This technique also works for snippets.

      The debugger offers various modes for dealing with Exceptions:

      • Pause on uncaught exceptions.
      • Pause on caught and uncaught exceptions.
      • Don’t pause on exceptions.

      2. Debugging From the Outside In

      When you have to debug a site which you have little insight into, you can use a different technique of debugging. In this approach, you hook into events you believe will trigger, and request DevTools breaks on such events if and when they occur. There are two categories of "outside > in" entry points:

      • DOM modifications
      • Event Listener breakpoints

      Break on DOM Modifications

      You have the task of debugging a web page, specifically the DOM. Nodes are added and removed during the lifecycle of the page, and you need to inspect the JavaScript which makes this happen. Set a DOM breakpoint with the following steps:

      • Right click on a DOM node in the Elements Panel.
      • Select a preferred DOM breakpoint from the Break on context menu.
      • While you are paused at a breakpoint, you can see a message which explains the reason the debugger has paused, as shown in Reason for pausing at a breakpoint.
      DOM modifications

      Every time you set a DOM breakpoint, you can easily toggle it on and off at the DOM breakpoints pane in the Elements Panel. In this pane, each breakpoint you set is listed, and you can interact with this pane in the following ways:

      • Toggle the checkbox on and off to enable or disable the breakpoint.
      • Click on the Node name (which is underlined) to navigate to it in the DOM tree view.
      • Right-click and select Remove All DOM breakpoints to disable and remove all DOM breakpoints.
      DOM breakpoints

      Subtree Modifications 

      Description: A Subtree modification occurs when the tree of a root node (which has the breakpoint set) is changed. This can include the addition or removal of nodes.

      Use case: An empty div container is present in the DOM, and an Ajax request happens on page load which appends some new nodes the the original container. Add a Subtree modification breakpoint on the container to see the exact point in code which adds new nodes to the DOM.

      Message examples: Paused on a Subtree Modified breakpoint set on body, because its descendant p was removed. Or: Paused on a Subtree Modified breakpoint set on div#parent, because a new child was added to that node.

      Attributes Modifications 

      Description: An Attribute modification triggers when an attribute name or value on a node is added, removed or modified. This includes all attributes, such as classdata-*, or style.

      Use case: A visual change happens on the page at a seemingly random point in time, and you narrow this down to a class which is dynamically set on the body element. You wish to investigate the cause of this dynamic class addition.

      Message example: Paused on an Attribute Modified breakpoint set on p.

      Node Removal 

      Description: A node removal breakpoint triggers at the point where a node is removed from the parent containing the set breakpoint.

      Use case: You are building a to-do list app and wish to verify that when a user deletes a to-do item, it is also removed from the DOM. You can set a node removal breakpoint to ensure this behaviour is occurs.

      Message example: Paused on a Node Removed div#container.

      Event Listener Breakpoints

      In the DevTools, a number of predefined Event Listener Breakpoints are available for you to enable. These offer entry points into the JavaScript that belongs to a page.

      Consider a simple about:blank page. Set a click event listener breakpoint on this page with the following steps:

      • Navigate to the Event Listener Breakpoints pane in the Sources Panel.
      • Open the Mouse Event Listener category.
      • Enable the Click event listener.

      You have now set a breakpoint. If you click on the page, notice that nothing happens. Now execute the following piece of JavaScript code in the Console Panel.

      document.addEventListener('click', console.log.bind(console))

      When you set a breakpoint for the same event you have registered an event listener for, the debugger pauses before the point where your event listener callback is executed.

      You can register breakpoints for many types of events such as timers, touch events and more, which are listed in the table below.

      Event CategoryEvent examples

      Animation

      requestAnimationFrame, cancelAnimationFrame, animationFrameFired

      Control

      resize, scroll, zoom, focus, blur, select, change, submit, reset

      Clipboard

      copy, cut, paste, beforecopy, beforecut, beforepaste

      DOM Mutation

      DOMActivate, DOMFocusIn, DOMFocusOut, DOMAttrModified, DOMCharacterDataModified, DOMNodeInserted, DOMNodeInsertedIntoDocument, DOMNodeRemoved, DOMNodeRemovedFromDocument, DOMSubtreeModified, DOMContentLoaded

      Device

      deviceorientation, devicemotion

      Drag / drop

      dragenter, dragover, dragleave, drop

      Keyboard

      keydown, keyup, keypress, input

      Load

      load, beforeunload, unload, abort, error, hashchange, popstate

      Mouse

      click, dblclick, mousedown, mouseup, mouseover, mousemove, mouseout, mousewheel, wheel

      Timer

      setTimer, clearTimer, timerFired

      Touch

      touchstart, touchmove, touchend, touchcancel

      WebGL

      webglErrorFired, webglWarningFired


      The "debugging from the outside in" technique can be useful when you need to debug a third-party website whose functionality has broken, or even when you are curious as to how something on a page you are viewing is working.

      3. Extensions

      A number of Chrome extensions exist, many of which enhance DevTools functionality. A featured list is found on the DevTools Extensions Gallery.

      DevTools JavaScript Preprocessing

      For DevTools Extension authors, the JavaScript preprocessing feature is a worthwhile topic to learn about. The preprocessor can intercept JavaScript source code before it enters the V8 engine, meaning JavaScript source code can be modified via DevTools before it enters the VM, all from an extension. 

      In addition to interception capabilities, the preprocessing API has programmatic access for reloading of script sources. An extension can, at any point during its lifecycle, reload a JavaScript source without reloading the original web page.

      4. Node

      This section covers a few tools which offer some level of integration between Node.js and the Chrome DevTools.

      Node Inspector

      There are two parts to the DevTools:

      • Front-end: This is what you use and interact with. It is composed of HTML, CSS, and JavaScript.
      • Back-end: In the case of inspecting a page in Google Chrome, the back-end is within the Chrome internals. Messages are passed back and forth via the Remote Debugging Protocol.

      Any application can implement communication over the remote debugging protocol and allow its users to debug via DevTools. Node Inspector is one such tool. After installing, you can run any node script using Node Inspector. The tool starts a web server which hosts the DevTools front-end. This special version of the DevTools doesn’t use the Chrome back-end, but rather Node Inspector’s own one.

      Node Inspector

      As you can see in Node Inspector, DevTools is paused at a breakpoint. The call stack refers to the calls executed in Node.js. The browser's only involvement here is for the DevTools UI.

      Node Heapdump

      Use Node Heapdump to take a snapshot of the V8 heap at a point in time in your code. The current state of the V8 heap is serialized and output to a file.

      Node Heapdump

      Compare two heap snapshots to discover which objects are not being garbage collected. This is useful for catching memory leaks.

      Conclusion

      That's it for this two-part series on a modern debugging experience. Hopefully at this point, you're comfortable with authoring and debugging JavaScript within the Chrome DevTools. You're familiar with workflows which can aid debugging and you know some tips and tricks when dealing with a production site you've not worked on before. Be sure to try some of the techniques you learnt here the next time you need to debug.

      Thank you for reading!

       

      0 Comments

      Leave a comment › Posted in: Daily

    1. Advantages and Disadvantages of WordPress Frameworks

      The concept of a framework is something that's very common both within the modern web and within the software development environments. For the front-end, we have frameworks like Bootstrap and Foundation, for web applications we have frameworks like Yii and Rails, and for desktop (and even some web applications) we have frameworks like .NET. And these are just to name a very small and select few.

      Generally speaking, frameworks are good: They provide a level of abstraction with which we, as developers, can work with in order to easily create generic functionality - such as user login and authentication - along with more specific code, such as logic that's specific to whatever the problem is that the software is aiming to solve.

      In short, Wikipedia defines a framework as follows:

      A software framework is a universal, reusable software environment that provides particular functionality as part of a larger software platform to facilitate development of software applications, products and solutions. Software frameworks may include support programs, compilers, code libraries, tool sets, and application programming interfaces (APIs) that bring together all the different components to enable development of a project or solution.

      As with many modern platforms, WordPress is no different. Of course, WordPress itself is not a framework - its an application that can be extended through the use of its many APIs. But there are a number of different frameworks that are available all of which aim to help ease the burden of writing a lot of repetitive code.

      But is this a good thing? That is, does it make sense to have so many choices of frameworks from which to choose as it relates to building WordPress themes, plugins, or web applications based on the platform?

      Usually, it depends on what you're trying to do. 

      Throughout the Tuts+ properties, we try to cover as many frameworks as possible - some for WordPress, some for the various languages and platforms that were mentioned earlier - but in this article, we're not going to be looking at a specific framework.

      Instead, we're going to be looking at the advantages and disadvantages of selecting a framework when working with WordPress to help make better decisions as it relates to building sites, applications, and other projects on top of WordPress.

      With WordPress, it's completely possible to mix various frameworks in order to achieve your end result, this article assumes that you're evaluating whether or not to use a single framework in order to help with your work.

      Comparing Frameworks

      As far as WordPress is concerned, there are currently (and generally) two types of frameworks:

      1. Drag and Drop Frameworks
      2. Options Frameworks

      Drag and Drop frameworks are usually related to building the user interface of a website. Often times, these come in the form of various pages in the WordPress Dashboard that allow you to arrange pre-defined elements on a page and have them render in said arrangement for the user to see.

      Options Frameworks, on the other hand, are usually used for code-specific functionality and usually provide some type of abstraction for one or more of the WordPress APIs. This includes, but is not limited to, the Settings API, the Meta Data API (for Posts, Users, Comments, and so on), and even some of the APIs related to templates.

      Whatever the case, there are both advantages and disadvantages that come with choosing a framework all of which are important to consider when determining whether or not you're going to work with or without a framework.

      Advantages

      Rapid Development

      One of the major advantages of using a framework is the speed at which you're able to assemble functionality. 

      Sometimes, people will refer to this as rapid prototyping, but WordPress frameworks have matured to a point such that you can often get away with creating full on interfaces, sites, and applications - not just prototypes - when working with the API.

      Though building content-driven sites with WordPress out-of-the-box is straightforward enough, many frameworks - especially drag and drop frameworks - make it that much faster to create more elaborate page layouts.

      Abstraction

      For frameworks that primarily deal with WordPress' APIs, frameworks can provide a nice level of abstraction such that much of the repetitive code that we're used to writing is tucked away within the framework.

      Perhaps one of the best examples comes when looking at frameworks for the Settings API. The Settings API, although powerful, is also verbose and cumbersome when it comes to getting elements to display on the screen. Frameworks seek to solve this problem by providing a way to more easily create settings, options, and settings with fewer function calls and clearer code.

      Of course, abstractions comes not just with the Settings API but for other APIs, as well. Opting to use one of these frameworks can save a lot of time and help ease the tedious nature that comes with working with some of the more repetitive aspects of WordPress-based code.

      Visual Representation

      Another advantage of using frameworks is that it helps bridge the gap between what we're expecting to happen and what really happens. 

      This is most easily seen within drag and drop frameworks: You have a predefined set of regions with which to work such as headers, sidebars, content areas, and footer areas, and then you place the regions where you'd like within a container. Once done, said regions appear exactly on the front-end as you've arranged them on the back-end.

      The same can also be said for API-specific frameworks, too. Although the visual nature of writing code isn't as clear as working with a page template editor, good frameworks can often provide clear classes, function names, and other facilities all of which help to more easily understand how all of the moving pieces of the software fit together.

      One such example may come in the form of creating a setting in the WordPress Dashboard. Say, for example, you want to introduce a textarea that is only going to support plain-text (that is, no markup or scripts allowed), and you need to label it, sanitize its data, validate its data, and display its data.

      Using a framework, what may take three different function calls and at least two callbacks to do can be done in a single function call with perhaps one or two callbacks. On top of that, the function names are a bit clearer and are more indicative of the work they're doing and the type of elements with which they're doing it.

      Disadvantages

      Dependency Management

      On the flip-side, if you opt to use a framework then you're automatically creating a dependency between yourself, third-party code, and WordPress.

      This means that if your code is based on a framework, and that framework is based on WordPress, then the abilities of the framework are limited only by the most recent version of WordPress that it supports.

      If the framework stays up to date with WordPress as it undergoes development, and the framework is released along with the major updates of WordPress, then keeping your code in sync with the most recent developments is easy.

      On the other hand, if the framework lags behind the most recent version of WordPress, then your code can only be as updated (and as secure and reliable) as the most recent version of WordPress that your framework supports.

      Deprecation

      Another challenge that comes with using frameworks is that, many times, frameworks are elaborate wrappers for existing functionality that exists within WordPress. To that end, there are going to be times where frameworks provide access to functions that may not always be available as WordPress is updated.

      Say, for example, you have a framework that provides access to a certain API that becomes deprecated in the latest version of the core application. Furthermore, the framework does not properly deprecate its code until another release cycle.

      This means that the code that you've written based on the framework is using deprecated function calls. For a release or two, this may not be a big deal, but once that functionality is gone from the core application and the framework hasn't addressed this, then you may not be able to use the latest version of WordPress or some of its newer features because the framework hasn't properly deprecated its code with that of core.

      Feature Limitation

      Frameworks can be really powerful, but when it comes to using them, it's often times a good idea to go "all-in." That is to say that when you use a framework, it's usually nice to write all of your code using the framework rather than some of the code using the framework and some of the code using the WordPress APIs. 

      In other words, you don't want to mix the code that you're writing such that you have a bit of a hodgepodge of code that's sort of based on a framework and sort of, you know, not based on a framework.

      After all, the purpose of a framework as defined earlier is to provide an abstraction for generic functionality.

      To that end, if a framework is incomplete or lacking functionality specifically for something that's provided with WordPress core, then you're left with one of two options:

      1. Forgo the feature that you want to use and wait for the framework to make it available,
      2. Side-step the framework and use core WordPress code alongside your framework-based code in order to achieve the desired result.

      Initially, it seems clear that if the framework doesn't offer something that you need, then simply use what WordPress provides. But when you do this, you're mixing the type of code that you're writing such that you're introducing a level of complexity when it comes to maintaining the software.

      If a framework later introduces a set of features that cover what you once wrote as vanilla WordPress code, you'll be tasked with updating said code to conform to that of the framework. From there, if the framework isn't continually updated to stay current with WordPress, then you're back at the dependency and deprecation problems.

      Conclusion

      It's not easy to outline all of the advantages and disadvantages that come with using a framework let alone make a choice on whether or not you should even use one, but the points mentioned above are some of the most common considerations anyone working with WordPress and frameworks should consider before selecting a framework and going all-in with it.

      Furthermore and as previously mentioned, this article isn't meant to provide an argument for or against using frameworks with WordPress. Instead, it's meant to provide both advantages and disadvantages for using frameworks in order to help you make a better decision as it relates to your work in WordPress.

      As with anything in development, there are going to be tradeoffs. It often comes down to what you're willing to tradeoff in favor of functionality, dependencies, and stability while balancing the core software that's always under development and has major releases roughly every six months.

      Depending on the nature of your work, a framework might be the way to go; for others, not so much. Whatever the case, make sure that you do your due diligence when deciding whether or not to use a framework in your current or upcoming projects.

       

      0 Comments

      Leave a comment › Posted in: Daily

    1. New Course: A Developer’s Guide to Setting Up a New Mac

      Getting a new Mac is a great thing for a developer, but it is also important to set up your computer with all the tools and utilities you need to do your job most effectively. In A Developer's Guide to Setting Up a New Mac, you'll see how to set up all the important tools that every developer needs.

      What You'll Learn

      In this course, you'll learn all about the many different tools that you can use to make your development environment the best it can possibly be. Tuts+ instructor Andrew Burgess will teach you about installing all the programs you need, and show you how to customize them to create a speedy, efficient workflow. 

      Here's a free preview of some of the lessons from this course:

      Terminal Customization

      The course includes a whole section on the terminal, covering things like installing iTerm, creating custom terminal prompts, and working with shell aliases and functions. In this lesson, you'll learn how to customize the look and feel of your terminal.

      Homebrew and Xcode Tools

      You can get even more out of the command line by installing the Xcode command line tools and Homebrew, the Mac OS X package manager. Find out how in this video.

      PHP and Apache

      In this lesson, you'll learn how to install the latest version of PHP with Homebrew, and make it work with the pre-installed version of Apache.

      Start Learning With a 14 Day Free Trial

      You can take the rest of this course straight away with a completely free 14 day trial of a Tuts+ subscription. Start your free 14 day trial today, to access this course and hundreds of others.

       

      0 Comments

      Leave a comment › Posted in: Daily

    1. Creating a Web App From Scratch Using AngularJS and Firebase

      In this series, we'll be using AngularJS and Firebase to create a simple web application from scratch. It will be a simple blogging application where the user can sign in or sign up and publish a blog post.

      This tutorial assumes you have basic knowledge of AngularJS, but it shouldn't be tough to pick up the topics along the way.

      Introduction to AngularJS

      AngularJS is one of the most sought-after JavaScript MVC frameworks. It's a structural framework for creating dynamic web applications by extending HTML capabilities. Features like data binding and dependency injection makes it easier to develop apps with less code.

      From the AngularJS documentation:

      HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

      Introduction to Firebase

      Imagine creating a web application without having to worry about the back-end side. Firebase makes it possible to sync data in real time with our application without bothering about the back-end. All we need to do is make some API calls.

      Firebase is a powerful API to store and sync data in real time. Combining the power of AngularJS two-way data binding with Firebase results in a three-way synchronization which is quite awesome.

      Getting Started With AngularJS

      The angular-seed project is a boilerplate to get started with creating web apps using AngularJS. Download or clone the angular-seed project from the repository. 

      $ git clone https://github.com/angular/angular-seed.git

      Navigate to the project directory and install the required dependencies.

      $ cd angular-seed
      $ npm install             ## Install the dependencies

      Start the node server:

      $ npm start               ## Start the server

      Point your browser to http://localhost:8000/app/index.html and you should see the default app running.

      Navigate to the app directory inside angular-seed. This is where the application code resides. Inside the app folder you'll find app.js which is the core of the app. We'll declare all the app-level modules and routes inside this file. By default, the angular-seed project has two views, view1 and view2. Delete the folders view1 and view2 from the app folder. 

      Let's start from scratch. Open up app.js and remove the existing code. In app.js we'll be defining our application routes, for example, how to handle a request like /home. In order to define routes, we'll need an AngularJS module called ngRoute. To use ngRoute we first need to inject it or add it into our application. We'll use angular.module to add the ngRoute module to our app as shown below: 

      angular.module('myApp', [
        'ngRoute'
      ])

      The ngRoute module has a component called $routeProvider which is useful for configuring routes. We'll inject $routeProvider into the config method of angular.module and define our routes in its callback function as shown below:

      'use strict';
      
      angular.module('myApp', [
        'ngRoute'
      ]).
      config(['$routeProvider', function($routeProvider) {
           // Routes will be here
      }]);

      Next, open up index.html and remove the script references to view1 and view2. Remove everything from the body of index.html except the script references and the div shown below with the ngView directive. 

      <div ng-view></div>

      ngView is a directive which helps to render the view attached with a particular route into the main layout, index.html. So each time the route changes, the content of the above shown div changes.

      Now let's create a new view for the user to sign in. Inside the app directory create a new folder called home. Inside home, create two files called home.html and home.js. Open up home.html and include the following HTML code:

      <!DOCTYPE html>
      <html lang="en" ng-app="myApp">
      
      <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <link rel="icon" href="http://getbootstrap.com/favicon.ico">
      
          <title>AngularJS & Firebase Web App</title>
      
          <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
          <link href="http://getbootstrap.com/examples/signin/signin.css" rel="stylesheet">
      
          <link href="justified-nav.css" rel="stylesheet">
      
      </head>
      
      <body>
      
          <div class="container">
              <div class="jumbotron" style="padding-bottom:0px;">
                  <h2>AngularJS & Firebase App!</h2>
              </div>
              <form class="form-signin" role="form">
                  <input type="email" class="form-control" placeholder="Email address" required="" autofocus="">
                  <input type="password" class="form-control" placeholder="Password" required="">
                  <label class="checkbox">
                      <a href="#"> Sign Up</>
              </label>
              <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
            </form>
      
          </div>
      
        
      
      </body></html>

      As seen in the above code, we'll be using Bootstrap to create our application views.

      Inside home.js, we'll declare the routes for the application to access the home view. $routeProvider  has a method called when, which we'll use to create a route for our home view. When defining a new route, we'll set a templateUrl which would be rendered in the index.html. Along with that, we'll also set a controller for the newly created $scope of the home view. A controller is a logic which controls a particular view. Here's how it should look:

      'use strict';
      
      angular.module('myApp.home', ['ngRoute'])
      
      // Declared route 
      .config(['$routeProvider', function($routeProvider) {
          $routeProvider.when('/home', {
              templateUrl: 'home/home.html',
              controller: 'HomeCtrl'
          });
      }])
      
      // Home controller
      .controller('HomeCtrl', [function() {
      
      }]);

      Now open up app.js and include the home module myApp.home in the app. Also declare the default route of our application using the $routeProvider.otherwise method to the home view.

      'use strict';
      
      angular.module('myApp', [
          'ngRoute',
          'myApp.home'           // Newly added home module
      ]).
      config(['$routeProvider', function($routeProvider) {
          // Set defualt view of our app to home
          
          $routeProvider.otherwise({
              redirectTo: '/home'
          });
      }]);

      Next, in order to display the homepage, we need to include home.js inside the main HTML template file of the app. Open up index.html and include the following:

      <script src="home/home.js"></script>

      Restart the server and point your browser to http://localhost:8000/app/index.html and you should see the sign-in screen:

      AngularJS  Firebase

      Getting Started With Firebase

      In order to get started, we'll need to register for a free account on Firebase. On successful signup, we'll get a screen like this:  

      Firebase Dashboard

      Make a note of the URL of the app created and click on the Manage App button. We'll be using this Firebase URL to interact with the Firebase database.

      We'll be using Firebase to authenticate our application using an email and password. In order to get it working, we need to enable it from Firebase. From the dashboard, click on the Login & Auth tab in the left-side menu. In that screen, under the Email & Password tab, check Enable Email & Password Authentication as shown:

      Enable Email  Password Authentication

      Add a new user with an Email and Password against which we'll authenticate after implementing the sign-in functionality.

      Add a new user with an Email and Password

      Implementing Sign-In Functionality

      In order to get started with using Firebase, include the following scripts in app/index.html:

      <script src="https://cdn.firebase.com/js/client/1.0.18/firebase.js"></script>
      <script src="https://cdn.firebase.com/libs/angularfire/0.8.0/angularfire.min.js"></script>
      <script src="https://cdn.firebase.com/js/simple-login/1.6.2/firebase-simple-login.js"></script>

      Next, we need to inject the firebase module in home.js. Add the firebase module in home.js as shown below:

      angular.module('myApp.home', ['ngRoute','firebase'])

      Now we are ready to interact with Firebase. Open up home.js and inside HomeCtrl, create a new function called SignIn to authenticate the user. We'll be using $scope to create the new function. $scope is an object that refers to the application model, and also acts as glue between the application controller and the view. Hence we'll inject the $scope object into the SignIn function so that the object model from view is accessible inside the SignIn function.

      $scope.SignIn = function($scope) {
          var username = $scope.user.email;
          var password = $scope.user.password;
          
          // Auth Logic will be here
      }

      Next, inside HomeCtrl create a Firebase instance using the Firebase URL as shown:

      var firebaseObj = new Firebase("https://blistering-heat-2473.firebaseio.com"); 

      The $firebaseSimpleLogin module is used to authenticate against Firebase using an email ID and password. To use it, we'll need to inject the $firebaseSimpleLogin module into HomeCtrl as shown:

      .controller('HomeCtrl', ['$scope','$firebaseSimpleLogin',function($scope,$firebaseSimpleLogin) {

      Using firebaseObj create a $firebaseSimpleLogin instance as shown:

      var loginObj = $firebaseSimpleLogin(firebaseObj);

      Now, using the $login API, we'll authenticate the email ID and password against Firebase. loginObj.$login takes in the email and password as parameters. On successful authentication, we get a success callback and on an unsuccessful authentication, we get an error callback. 

      $scope.SignIn = function(event) {
          event.preventDefault();  // To prevent form refresh
          var username = $scope.user.email;
          var password = $scope.user.password;
          
          loginObj.$login('password', {
                  email: username,
                  password: password
              })
              .then(function(user) {
                  // Success callback
                  console.log('Authentication successful');
              }, function(error) {
                  // Failure callback
                  console.log('Authentication failure');
              });
      }

      Now for all the above controller code to work, we need to attach the controller to the view. AngularJS provides a directive called ngController to attach a controller to a view. Open up home.html and add the ngController directive to the body element to attach it to HomeCtrl.

      We need the email and password values to be accessible inside the SignIn controller function. AngularJS provides a directive called ngModel to bind its value to $scope so that it's accessible inside the SignIn function. Include the ngModel directive to the email and password input elements as shown:

      <body ng-controller="HomeCtrl">
      
          <div class="container">
              <div class="jumbotron" style="padding-bottom:0px;">
                  <h2>AngularJS & Firebase App!</h2>
              </div>
              <form class="form-signin" role="form">
                  <input ng-model="user.email" type="email" class="form-control" placeholder="Email address" required="" autofocus="">
                  <input ng-model="user.password" type="password" class="form-control" placeholder="Password" required="">
                  <label class="checkbox">
                      <a href="#"> Sign Up</>
              </label>
              <button type="button" class="btn btn-lg btn-primary btn-block">SignIn</button>
            </form>
      
          </div>
      
        
      
      </body>

      Finally, add the ngClick directive to the sign-in button to call the SignIn function:

      <button type="button" ng-click="SignIn($event)" class="btn btn-lg btn-primary btn-block">SignIn</button>

      Save all the changes and restart the server. Point  your browser to http://localhost:8000/app/index.html#/home and try to sign in using the email ID jay3dec@gmail.com and password jay. On successful user authentication, you should see the message Authentication successful in the browser console.

      Conclusion

      In this tutorial, we reviewed how to get started with creating an AngularJS web application. We implemented the sign-in functionality and successfully authenticated the user against the Firebase database. 

      In the second part of this tutorial, we'll take this to the next level by implementing validations, sign-up functionality, and some other features. Code from the above tutorial is available on GitHub.

      Do let us know your thoughts in the comments below.

       

      0 Comments

      Leave a comment › Posted in: Daily

  • Page 1 of 35 pages  1 2 3 >  Last ›
  • Browse the Blog

    Syndicate

    governing-bruise