VOOZH about

URL: https://dzone.com/users/935799/paulund1.html

⇱ Paul Underwood - DZone Member


Paul Underwood

Web Developer at Paulund

Worle, GB

Joined Sep 2011

About

Paulund is a website dedicated to writing tutorials and code snippets about Web Development, the main subjects are PHP, Wordpress, jQuery, CSS3 and HTML5.

Stats

Reputation: 436
Pageviews: 2.6M
Articles: 36
Comments: 0

Articles

How to Capitalize the First Letter of a String in JavaScript [Snippets]
A small and practical tutorial on building code for this handy little function.
Updated August 27, 2019
Β· 375,173 Views Β· 2 Likes
CSS Bouncing Arrow
In this tutorial, we're going to learn how you can create an animated bouncing arrow by using CSS.
September 29, 2016
Β· 20,372 Views Β· 2 Likes
How to Reverse jQuery SlideUp and SlideDown
We take a look at how to reverse the purposes of jQuery's slideUp and slideDown methods. Read on for some code and explanations!
September 16, 2016
Β· 21,549 Views Β· 3 Likes
Configuring Multiple Database Connections in Lumen
Connecting to one database in Lumen is easy enough, but what about connecting to multiple databases? Come find out how to handle this situation.
July 8, 2016
Β· 23,476 Views Β· 3 Likes
List of All Countries in JSON
Ever created a sign-up form that required a dropdown for the user to select from a list of countries? This JSON snippet might come in handy!
June 15, 2016
Β· 132,936 Views Β· 12 Likes
Increment Numeric Part of String
Ever wondered how to easily increment a number that's part of a string? Check out how to quickly do this in PHP!
May 13, 2016
Β· 12,994 Views Β· 2 Likes
Get WordPress Image ID by URL
In a recent project, I needed to automatically assign an image to a post from a URL. So, how did we solve this problem? Read on to find out.
March 28, 2016
Β· 11,297 Views Β· 4 Likes
Using the jQuery .each() Function (with Examples)
With jQuery dominating JavaScript development, this article is a deep dive into one of the main functions in the libraryβ€” each().
February 26, 2016
Β· 99,117 Views Β· 3 Likes
Get Last Record in Each MySQL Group
In this tutorial we will look at how you can use MySQL at getting the last record in a Group By of records.
September 4, 2015
Β· 106,664 Views Β· 5 Likes
Populate a jQuery Dropdown From AJAX
This quick snippet will show you how to handle the AJAX request for a jQuery drop-down menu and populate it with the response.
August 5, 2015
Β· 124,149 Views Β· 3 Likes
Fixed Width Sortable Tables Row with jQueryUI
When you use jQuery UI sortable function on a table I've noticed that it will collapse the width of the row you're dragging which can lead to a strange user experience. In this tutorial we are going to see how you can use a helper function to change the width of dragging rows back to the original width. Have a look at the demo to see the difference. Demo jQuery Sortable is part of the jQuery UI library which can be found below. jQuery Sortable To define a table to have sortable rows all you have to do is apply the sortable method to the parent element of the row, which normal would be the table itself or ideally the table body. FilmDateRatingThe Shawshank Redemption19949.2 Then you can make the table body rows sortable by using the following jQuery code. $('table tbody').sortable(); One of the options you can use on the sortable method is helper property where you can define a function to run when dragging the display. Therefore we simply need to create a function that will reset the width of the table row by simply using the function below. $('table tbody').sortable({ helper: fixWidthHelper }).disableSelection(); function fixWidthHelper(e, ui) { ui.children().each(function() { $(this).width($(this).width()); }); return ui; } Demo
April 27, 2015
Β· 19,450 Views
Register Hidden Fields On Ninja Forms
When you are building a website, one of the most important areas of your site are forms, allowing you to capture data about your audience it can help you know what they want from you. There is no built in way in WordPress to create forms for your site, but there are a few really good plugins that allow you to do this. The one I've been using recently is a plugin called Ninja Forms, it allows you to create forms in the admin area by dragging the fields you want into position on the form and display them in either the sidebar or content area of your site. Ninja Forms In this tutorial we are going to look at creating custom fields to the form so that you can collect more information about the user such as IP address and the page the form was filled out. Create New Field Elements There is a function that is included in Ninja Forms called ninja_forms_register_field that allows you to programmatically create new fields that you can use on the drag and drop interface to add onto your form. The following code will use this function to create two new fields one to collect the IP address and the other to collect the page the form was filled out on. The important parameter to note here is the display_function, this will define the callback function to display the form element. function register_ninja_form_fields() { $argsIp = array( 'name' => 'User IP', 'display_function' => 'collect_user_ip_display', 'sidebar' => 'template_fields', 'display_label' => false, 'display_wrap' => false, ); $argsPage = array( 'name' => 'Page', 'display_function' => 'collect_user_page', 'sidebar' => 'template_fields', 'display_label' => false, 'display_wrap' => false, ); if( function_exists( 'ninja_forms_register_field' ) ) { ninja_forms_register_field('user_ip', $argsIp); ninja_forms_register_field('user_page', $argsPage); } } add_action( 'init', 'register_ninja_form_fields' ); Next we need to create the functions which are used in the callback when creating the fields for the form. Create User ID Element Below is the code you need to display the hidden field that is the User IP address. We need to do a check to see if the field is on a page or not, this is because in the backend of the form area you can display the submission values for the form. The problem you will have is because we are using hidden fields you won't be able to see the IP address when looking at the form submissions, therefore we need to change the field to a text box in the admin area. The way we will do this is by checking if the global $post variable is set, if it isn't set then we can display the form in a text box. function collect_user_ip_display( $field_id, $data ) { global $post; $id = $_SERVER["REMOTE_ADDR"]; if(!empty($post)) { ?> User IP Find out more about this person Page Form Submitted
March 29, 2015
Β· 7,453 Views
Dynamically Create CSS Classes With SASS
There are many advantages to using CSS pre-processors like SASS, some of the features allow you to end up writing less CSS code by using inheritance and functions in SASS to reuse the same code on your different CSS classes and IDs. To learn more about getting started with SASS you can refer to a previous articles. Getting started with SASS One of my favourite features of SASS is the ability to use loops to dynamically create your CSS classes. A good example of this is when you want to make a set of classes to use for changing the text colours and background colours of elements you would normally have to write CSS like this. .red-background { background: #FF0000; } .red-color { color: #FF0000; } .blue-background { background: #001EFF; } .blue-color { color: #001EFF; } .green-background { background: #00FF00; } .green-color { color: #00FF00; } .yellow-background { background: #F6FF00; } .yellow-color { color: #F6FF00; } If you want to add additional colours to this later you will have to remember to write both background and colour classes. With SASS we can create a list of our colours and then loop through these to create the CSS classes. To create a list in SASS all you have to do is create a comma separated list of key value pairs like the following. $colours: "red" #FF0000, "blue" #001EFF, "green" #00FF00, "yellow" #F6FF00; Using the @each keyword in SASS we can loop through each of the colours and then use the nth() function to get the name of the class and the value of the class to dynamically create the classes in our CSS. The following each loop will generate exactly the same colour classes as above with only a few lines of code. @each $i in $colours{ .#{nth($i, 1)}-background { background: nth($i, 2); } .#{nth($i, 1)}-color { color:nth($i, 2); } }
July 4, 2014
Β· 16,277 Views
Checking Media Queries With jQuery
With the web being used on so many different devices now it's very important that you can change your design to fit on different screen sizes. The best way of changing your display depending on screen size is to use media queries to find out the size viewport of the screen and allowing you to change the design depending on what screen size is on. You will mainly make these changes in the CSS file as you can define the media query break points to change the design on different devices like this. /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { } /* Desktops and laptops ----------- */ @media only screen and (min-width : 1224px) { } /* Large screens ----------- */ @media only screen and (min-width : 1824px) { } The above code will allow you to make styling completely different on different devices, but what if you wanted to change the functionality of the site depending on the screen size? What if you needed to use some Javascript code on different screen sizes, for example to create a slide down navigation button. How Do You Use Media Queries With jQuery Media queries will be checking the width of the window to see what the size of the device is so you would think that you can use a method like .width() on the window object like this. if($(window).width() < 767) { // change functionality for smaller screens } else { // change functionality for larger screens } But this will not return the true value of the window as it takes into effect things like body padding and scroll bars on the window. The other option you have when checking the media size is to use a Javascript method of .matchMedia() on the window object. var window_size = window.matchMedia('(max-width: 768px)')); This works the same way as media queries and is supported on many browsers apart from IE9 and lower. Can I Use window.matchMedia To use matchMedia you need to pass in the min or max values you want to check (like media queries) and see if the viewport matches this. if (window.matchMedia('(max-width: 768px)').matches) { // do functionality on screens smaller than 768px } Now you can use this to add a click event on to a sub-menu for screens smaller than 768px. The below code is an example of how you can add some Javascript code which will only be run on screens smaller than 768px. if (window.matchMedia('(max-width: 768px)').matches) { $('.sub-menu-button').on('click', function(e) { var subMenu = $(this).next('.sub-navigation'); if(subMenu.is(':visible')) { subMenu.slideUp(); } else { subMenu.slideDown(); } return false; }); }
June 6, 2014
Β· 135,718 Views Β· 3 Likes
Load Scripts Dynamically With jQuery
A common tactic to help speed up your website is to use a technique called lazy loading which means that instead of loading everything your page needs at the start it will only load resources as and when it needs them. For example you can lazy load images so you can start the page off only with the images you need to view the page correctly, then other images that are out of view you won't need to load straight away. As the user scrolls down the page you can then search to see if the images are about to come into view and lazy load the images when they are needed. You can do the same with other resources such as JavaScript or CSS files, you can make sure you only load in the script as and when they need them to be used. An example of this I have used in the past is loading Disqus comments on the click event of a button, this jQuery code will then load in the Disqus Javascript file and initialise the Disqus code on the selected div. $j=jQuery.noConflict(); $j(document).ready(function() { $j('.showDisqus').on('click', function(){ // click event of the show comments button var disqus_shortname = 'enter_your_disqus_user_name'; // Enter your disqus user name // ajax request to load the disqus javascript $j.ajax({ type: "GET", url: "http://" + disqus_shortname + ".disqus.com/embed.js", dataType: "script", cache: true }); $j(this).fadeOut(); // remove the show comments button }); }); Ajax Method As you can see from the code above we have a click event of the .showDisqus button, inside this using the jQuery method .ajax() which is making a GET request for the script of embedding Disqus into your application. The ajax method is normally used to make basic http requests to a server side script and return the output of the script. On this occasion we are making a GET request and setting the dataType to be a script. This tells jQuery to treat the return as if we are including a new JavaScript file, this will disable browser caching on the script by adding a timestamp parameter to the end of the script. If you would like to enable caching of the script then you need to make sure you include a cache: true parameter. $.ajax({ type: "GET", url: "http://test_script.js", dataType: "script", cache: true }); Get Script Method Another option to get the script via GET ajax is to use the method getScript() this is simply a wrapper for the above ajax method. $.ajax({ url: url, dataType: "script", success: success }); This allows you to reduce the amount of code you are writing by simply using this method. $.getScript( "http://test_script.js" ) .done(function( script, textStatus ) { alert('Successfully loaded script'); }) .fail(function( jqxhr, settings, exception ) { alert('Failed to load script'); }); The problem with using getScript() is that it will never cache the script as it will always add the timestamp querystring to the end of the JavaScript file. As the ajax() method allows you to choose if you cache the script or not it is better to use this method when loading in a script that will not change.
June 4, 2014
Β· 17,525 Views
Update Row With Highest ID In MySQL
Recently needed to update the last inserted row of a table but didn't have anyway in knowing what the highest ID in the table was. I can easily do this by using the max() function to select the highest ID in the table. SELECT MAX(id) FROM table; Then I can use the result of this query in the UPDATE query to edit the record with the highest ID. But this is quite a easy query so I should be able to do this in one query by using a nested select query on the UPDATE. UPDATE table SET name='test_name' WHERE id = (SELECT max(id) FROM table) But the problem with this is that the MAX() function doesn't work inside a nested select so had to find another way of doing this. I found out that you can use an ORDER BY and a LIMIT in an UPDATE query therefore I can use a combination of these in the UPDATE query to make sure I only update the record with the highest ID, by doing a descendant order on the ID and limiting the return to only 1 record. UPDATE table SET name='test_name' ORDER BY id DESC LIMIT 1;
April 23, 2014
Β· 21,566 Views
How to Re-Render Prism.js on New Code
I recently switched to use a new syntax highlighter called Prism.js. Unlike other highlighters, Prism.js is extremely lightweight by default, and you can append additional add-ons to library for more options or new themes. There are currently six different themes that you can choose from, and you can select which themes to include with the package at download. You can choose to just download the default theme or include all themes. Prism.js is designed to be very lightweight so adding additional features and themes will therefore increase the size of the package. Prism.js Like other syntax highlighters, this is designed to change the code inside pre and code tags on load to display the code like it would look if the code was inside a code editor. The important part here is that on the page load event, this becomes a problem if you are using a syntax highlighter to display code you are creating with Javascript or content you load in with AJAX. Therefore you need a way of re-rendering the Prism object again to render all code on the page. When you include Prism Javascript files on the page it will create a Prism object. This has access to a number of different methods that you can use to update the code inside the pre and code tags. Using the method highlightAll(), Prism will go through the page and search for pre and code tags and re-render all of them to style them correctly. Prism.highlightAll(); If you only want to re-render a single element, you can select this element with Javascript and send this as a parameter into the highlightElement() method. var precode = document.getElementById('application-code') Prism.highlightElement(precode); Prism Documentation
October 22, 2013
Β· 9,618 Views
The Ups and Downs of PHP Template Engines
A PHP template engine is a way of outputting PHP in your HTML without using PHP syntax or PHP tags. It's supposed to be used by having a PHP class that will send your HTML the variables you want to display, and the HTML simply displays this data. This means that you are forced to separate your PHP logic from the HTML output, which is great; separation in your code is what you should be aiming for. The best way to understand what a template engine does it to see the code. Below is a basic page where you might want to display a title and a list of products. getAllProducts(); ?> title; ?> description; ?> The idea of using a template engine is that you would remove the $title variable and the $products variable and put this in a class, and then call a template file to display the HTML. getAllProducts(); $this->renderHtml('all-products.html', $vars); } } ?> The renderHtml() method will pass in the variables you want to display to the template file, which will look similar to this. {{ title } {% for product in products %} {{ product.title } {{ product.description } {% else %} No products exist. {% endfor %} As you can see, there is a separation of the PHP logic and display of code. Another reason why you might use a template engine is because now you have an HTML view file, which you can give to your front-end developer to style, and a template engine is arguably easier to read than using PHP syntax. What Frameworks Currently Use Template Engines? There are a few large frameworks that currently use a template engine. Some that I've used are Laravel, Drupal 8 and Expression Engine. All of these use different template engines but the understanding of how they work is similar. Laravel - Blade Templating Laravel uses a template engine called Blade. Here is an example of how you will use blade in your HTML views. @section('sidebar') This is the master sidebar. @show @yield('content') Output a Variable {{ $val } Foreach Loop @foreach ($users as $user) {{ $user->name } @endforeach If/else Statement @if ($user->name == 'Dave') Welcome Dave! @else Welcome Guest! @endif Blade Templating Drupal - Twig The Drupal CMS uses a template engine called Twig. This was developed to make templating quicker and more secure. It works in a similar way as blade but the syntax is slightly different. Output a Variable {{ var } For Loop {% for user in users %} * {{ user.name } {% else %} No user have been found. {% endfor %} Inherit Templates {% extends "layout.html" %} {% block content %} Content of the page... {% endblock %} Twig Smarty Another populate template engine is called Smarty. Again, Smarty was developed for code and HTML separation, and to make your templates easier to read. Output a Variable {$name} Foreach Loop {foreach $users as $user} {strip} {$user.name}{$user.phone} {/strip} {/foreach} If Statement {if $name == 'Fred'} Welcome Sir. {elseif $name == 'Wilma'} Welcome Ma'am. {else} Welcome, whatever you are. {/if} Smarty Using a Template Engine The three examples of template engines I gave above are not the only template engines available. There are many, and not just for PHP. Lots of other languages can use a template engine. Even though they are different engines, they are all similar in a way; they were all developed to make front-end templating quicker and easier to read. They all mention that this forces separation of your code and makes HTML easier to read, because you don't have any PHP tags in your HTML. But when I work with these different engines, I never enjoy developing with them. I actually find that they drastically slow down my development because I now have to look up the Smarty syntax or the Twig syntax for the thing I want to do. What they mention about code separation is exactly right; you shouldn't have logic in your HTML. However, you don't need a templating system to do this. In a previous tutorial I demonstrated how you can separate your HTML from your code with a simple method using output buffering. Separate HTML From Code So, while dealing with logic separation is up to the developer to do properly, the benefit of a template language is that it enforces it. If you're worried about separation you can use an MVC framework, or just create a method, and use the ob_buffer to get the HTML contents. If a developer is going to add log-in to an HTML file, they can't complain about separation and not being able to debug easily. I also don't agree with what's mentioned about the template engines being easier to read. Take a foreach in blade for an example of the difference: name; ?> @foreach ($users as $user) {{ $user->name } @endforeach There's not much difference between these code samples, except in Blade you use: {{ $user->name } In PHP, on the other hand, you use: name; ?> I even made the PHP do more than I have to. I could have simply used the printf() function to output the div, so it would look like this: %s', $user->name); } ?> Is it really so difficult to read that we have to learn a whole new template language to output variables in your HTML? I don't think so. Benefit of Using a Template Engine In my experience, there isn't a benefit to using a template engine over native PHP templating, but there must be some benefit, or there would be no reason to use it. So, I asked this question on Google+: what is the benefit or using a template engine? One of the answers I had directed me to this post on stackoverflow explaining some of the benefits of using a template engine. Some of the benefits mentioned are: New syntax Automatic escaping Template inheritance Ease of reading for non-developers Now, I would argue that learning a new syntax is not a benefit. Having to look up the correct syntax every time I need to do a foreach loop or an if statement is going to take up so much more time than simply using PHP. Automatic escaping is a real benefit. So many developers forget to escape when outputting content on the page, and this takes care of that for you. But it's really not that difficult to create a function that will escape the content of a variable. If you want some good examples, there's a formatting file (/wp-includes/formatting.php) in WordPress with loads of escaping functions you can use in different situations. Then you make sure you escape your content before sending it to the view. Template inheritance is another good benefit for some pages, and could be used for skinning different areas of the site. The ease of reading for non-developers is the one I disagree with most. PHP is not a hard language to read. It's not even a hard language to learn. If you have a front-end developer that is changing your HTML and can't understand what you're doing with the PHP, then I would recommend that they go and learn the basics of PHP. I'm not saying they need to learn how everything works and OOP principles, but just the basics so they can identify what an if statement is, what a for loop is, and so on. The native PHP syntax is not that different from the template engine syntax, so if they can learn that, then they most certainly can learn PHP syntax. For me, the only real benefit to using a template engine is security and autoescaping the output of the HTML. I'm not here to discourage people from using template engines; I can see they have their place, but like anything, you have to use them on the right projects. It depends on your team for the project, the size of the application, who's coding the HTML and whether the content author will want to change the HTML. In some cases, template engines might be perfect for your project. Here is a good article for reasons why you should be using template engines: Template Engines In PHP. In conclusion, I'm not really a fan of these template engines. For me, they just add another layer, another language you need to learn with little benefit. So, am I going to use these in my future projects? I'm still undecided. I can see they have a place and a reason for being used, but I think things take longer when developing with them, and they're not easy to debug.
September 24, 2013
Β· 17,548 Views
Remove Characters at the Start and End of a String in PHP
In a previous article about how you can remove whitesapce from a string, I spoke about using the functions ltrim() and rtrim(). These work by passing in a string to remove whitespace. Using the ltrim() function will remove the whitespace from the start of the string, using the rtrim() function will remove the whitespace from the end of the string. But you can also use these functions to remove characters from a string. These functions take a second parameter that allows you to specify what characters to remove. // This will search for the word start at the beginning of the string and remove it ltrim($string, 'start'); // This will search for the word end at the end of the string and remove it rtrim($string, 'end'); Remove Trailing Slashes From a String A common use for this functionality is to remove the trailing slash from a URL. Below is a code snippet that allows you to easily do this using the rtrim() function. function remove_trailing_slashes( $url ) { return rtrim($url, '/'); } A common use for the ltrim() function is to remove the "http://" from a URL. Use the function below to remove both "http" and "https" from a URL: function remove_http( $url ) { $url = ltrim($url, 'http://'); $url = ltrim($url, 'https://'); return $url; }
August 20, 2013
Β· 41,688 Views
Remove Automatic Paragraphs In Shortcodes
This post is an extension to the post I wrote some time ago about displaying code snippets on a WordPress site. That post showed how you can create a WordPress plugin that makes a shortcode for a number of different languages that will encode the content so that you can display code snippets on your WordPress site. Using this plugin, you will have access to four shortcodes: HTML, CSS, JavaScript and PHP. HTML .css_class { } var js = document.getElementById('element'); But because we were encoding the content using htmlentities it caused some problems with the way WordPress renders content. WordPress will automatically change double line-breaks to paragraph tags. In this article, we will see what those problems are and come up with a solution to solve them. WordPress Automatic Paragraphs When WordPress displays your content on the page it will run it through two different filters: wptexturize and wpautop. wptexturize is a filter that will convert all quotes into smart quotes. It will also convert apostrophes, dashes, ellipses, the trademark symbol and the multiplication symbol. Because code normally uses straight quotes instead of curly quotes, text inside pre and code tags are ignored. wpautop is a filter that will change double line-breaks into paragragh tags. When you add a new line while using the tinyMCE editor, it will create a double line-break, so this filter solves that problem. This is a problem inside shortcodes that are running the content through the htmlentities() function because it will convert the HTML so it is shown in the shortcode content area. Therefore, if you create a shortcode to display HTML like this: [ html ] [ /html ] Because we have line breaks in this shortcode by going to a new line, wpautop() will try to convert this text. Since we are using htmlentities on the content of the shortcode, the output will display these paragraph tags and line break tags. What will actually be returned from the shortcode is this: You can see the closing paragraph tag and the line break at the end of the line with the div element. If you are trying to display more information, such as a CSS class with a line break on each property, it will be displayed this way: .alert-danger,<;br /> .alert-error { color: #b94a48; background-color: #f2dede; border-color: #eed3d7; } Turning Off wpautop() Removing these line breaks and paragraph tags from the content is very easily done in WordPress. All we have to do is make sure the content doesn't go through the wpautop filter by removing it. To remove a filter in WordPress, all you have to do is use the function remove_filter(), pass in the tag of the_content and remove the function wpautop. remove_filter('the_content', 'wpautop'); But if we use this function to remove the wpautop() then it will be removed for all content, which will remove all paragraphs in your content, which makes your content unreadable. In order to display code snippets correctly, we need to find a way of solving this problem without turning off wpautop() on all content. We will only want to turn this off on content inside shortcodes. Removing wpautop() from Content Only in Shortcodes To remove the wpautop() function only in shortcodes we need to create a brand-new filter through which to run all of our content. First, we turn off wpautop filters and wptexturize filters on all content. remove_filter('the_content', 'wpautop'); remove_filter('the_content', 'wptexturize'); This new filter will need to check to see how the content is being displayed. If the content is inside a shortcode, then it won't run through the wptexturize and wpautop functions. If the content is not inside the shortcodes, then it will apply the wptexturize and wpautop functions. function remove_auto_p_in_shortcode_formatter($content) { $new_content = ''; $pattern_full = '{(\[raw\].*?\[/raw\])}is'; $pattern_contents = '{\[raw\](.*?)\[/raw\]}is'; $pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE); foreach ($pieces as $piece) { if (preg_match($pattern_contents, $piece, $matches)) { $new_content .= $matches[1]; } else { $new_content .= wptexturize(wpautop($piece)); } } return $new_content; } add_filter('the_content', 'remove_auto_p_in_shortcode_formatter', 99); Now, all the code inside shortcodes will not have a trailing paragraph tag and you will no longer have line breaks at the end of your code snippets. If you'd like a copy of the syntax highlighter used on Paulund, it is available on GitHub as a WordPress plugin. Paulund Syntax Highlighter
August 8, 2013
Β· 10,226 Views
How To Compare Strings In PHP
During any sort of programming you will always get situations where you need to compare values with each other, if the values are boolean or integers then the comparison is simple. But if you want to compare strings or parts of strings then there can be more to the comparison such as case of the string you are comparing. In this tutorial we are going to look at all the different ways you can compare strings in PHP using a number of built in PHP functions. == operator The most common way you will see of comparing two strings is simply by using the == operator if the two strings are equal to each other then it returns true. if('string1' == 'string1') { echo ' Strings match. '; } else { echo ' Strings do not match. '; } This code will return that the strings match, but what if the strings were not in the same case it will not match. If all the letters in one string were in uppercase then this will return false and that the strings do not match. if('string1' == 'STRING1') { echo ' Strings match. '; } else { echo ' Strings do not match. '; } This means that we can't use the == operator when comparing strings from user inputs, even if the first letter is in uppercase it will still return false. So we need to use some other function to help compare the strings. strcmp Function Another way to compare strings is to use the PHP function strcmp, this is a binary safe string comparison function that will return a 0 if the strings match. if(strcmp('string1', 'string1') == 0) { echo ' Strings match. '; } else { echo ' Strings do not match. '; } This if statement will return true and echo that the strings match. But this function is case sensitive so if one of the strings has an uppercase letter then the function will not return 0. strcasecmp Function The previous examples will not allow you to compare different case strings, the following function will allow you to compare case insensitive strings. if(strcasecmp('string1', 'string1') == 0) { echo ' Strings match. '; } else { echo ' Strings do not match. '; } if(strcasecmp('string1', 'String1') == 0) { echo ' Strings match. '; } else { echo ' Strings do not match. '; } if(strcasecmp('string1', 'STRING1') == 0) { echo ' Strings match. '; } else { echo ' Strings do not match. '; } All of these if statements will return that the strings match, which means that we can use this function when comparing strings that are input by the user.
June 25, 2013
Β· 80,956 Views
Automatically Detect Browser Language With PHP
When you are working on a multinational website you may need the functionality to translate your website into different languages. There are many ways you can translate a website, in this article I will not go through the different ways you can translate a website. But one thing is that you will always need is to know what language you want display when a user hits your page. There are different options you can do with this, either have a default language and allow the user to switch to the language they want to use, or detect the language set in the browser and switch the language automatically. You can detect the language the browser is set to by looking at the server variable HTTP_ACCEPT_LANGUAGE. // Detect browser language $_SERVER['HTTP_ACCEPT_LANGUAGE']; This variable will display all the languages that you can set in your browser en-GB,en,en-US. But because you can select multiple languages for your browser they are returned as a comma separated string. From these languages you can explode the string and now you have a list of all languages that the user can read, looping through this list you can find supported languages and display these to the user. $supportedLangs = array('en-GB', 'fr', 'de'); $languages = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']); foreach($languages as $lang) { if(in_array($lang, $supportedLangs)) { // Set the page locale to the first supported language found $page->setLocale($lang); break; } }
June 22, 2013
Β· 27,772 Views
How To Find Events Bound To An Element With jQuery
In this tutorial we are going to investigate ways you can tell what events a certain element has bound to it. This is really useful when you need to debug the on method to see how it is working. There are a number of ways to bind events to an element, there is bind(), live() and delegate(). Bind - Used to attach events to current elements on the page. If new elements are added with the same selector the event will not be added to the element. Live - This is used to attach an events to all elements on the page and future elements with the same selector. Delegate - This is used to attach events to all elements on the page and future elements based on a specific root element. As of jQuery 1.7 the on method will give you all the functionality that you need to bound events to elements. It will allow you to add an event to all elements on the page and all future elements. $('.element').on('click', function(){ // stuff }); $('.element').on('hover', function(){ // stuff }); $('.element').on('mouseenter', function(){ // stuff }); $('form').on('submit', function(){ // stuff }); When you are assigning events to future elements you might want to find out what events are currently assigned to these elements. Using developer tools in your browser you can see what events are currently bound to the element by using these 2 methods. First you can display the events by using the console, the second method is to view the events in the event listener window in the developer tools. Display Events In Console In your browser if you press F12 a new window called developer tools will open, this allows you to view the entire HTML DOM in more detail, this also has a console feature which will allow you to type in any Javascript to run at this current time on the page. You can use the console to display a list of events currently assigned to an element by using the following code. $._data( $('.element')[0], 'events' ); This will display all the events that are currently assigned to the element. Event Listener Window The other option to use to view what events are currently assigned to an element is to use the event listener window in your browser's developer tools. All you have to do is press F12 to open the developer tools, select the element in the HTML DOM that you want to investigate, on the right side of the window you will see an option called Event Listeners. When you expand this menu you will see all the current events assigned to the element including all click events bound from jQuery.
May 29, 2013
Β· 51,982 Views
Resize Image Class With PHP
A common feature that you will come across in websites is the ability to resize an image to fit an exact size so that it will be displayed correctly on your design. If you have a very large image and you are going to place it on your website in a space that is only 100px x 100px then you will want to be able to resize this image to fit in the space. One option is to just set the width and height attributes on the image tag in your HTML, this will force the image to be displayed at this size. This will work perfectly fine and the image will fit in the 100px x 100px space but the problem is that when the browser loads the image it will not resize the image but will just display it in the limited size. This means that the image will still need to be downloaded at full size, if the image is very large it can take some time for you to download a large image just to be displayed in a small space. A better solution would be to resize the image to 100px x 100px which will reduce it's size so that the browser doesn't need to download a large image just to display it in a small space. In this tutorial we are going to create a PHP class that will allow you to resize an image to any dimension you want, it will allow you to resize while keeping the aspect ratio of the image. When the class has resized the image you can either save the image on the server or download the image. Class Methods First lets plan out the class we are going to create: We need to pass an existing image to the class, this is the image that we will use to resize. We need to pass in the desired image dimensions so the class can work out what's the new size of the image. Then we need to be able to save the image to a location on the server, and choose to download the image. The Constructor This class relies on an original image being found and set on the class, without this the class will not work correctly. Because of this we should pass the image filename into the constructor of the class. This will then check if the file exists on the server, if it does then we can call the set image method where we can get the image and create a resource of the image and store this in a class variable. /** * Class constructor requires to send through the image filename * * @param string $filename - Filename of the image you want to resize */ public function __construct( $filename ) { if(file_exists($filename)) { $this->setImage( $filename ); } else { throw new Exception('Image ' . $filename . ' can not be found, try another image.'); } } Set The Image The set image method is used to create a image resource based on the image given to the class this uses the PHP functions imagecreatefromjpeg, imagecreatefromgif, imagecreatefrompng to create the image resource from the given image. We can then use this with the functions imagesx and imagesy to return the current width and height of the image. This will allow us to resize the image easier later in the script. /** * Set the image variable by using image create * * @param string $filename - The image filename */ private function setImage( $filename ) { $size = getimagesize($filename); $this->ext = $size['mime']; switch($this->ext) { // Image is a JPG case 'image/jpg': case 'image/jpeg': // create a jpeg extension $this->image = imagecreatefromjpeg($filename); break; // Image is a GIF case 'image/gif': $this->image = @imagecreatefromgif($filename); break; // Image is a PNG case 'image/png': $this->image = @imagecreatefrompng($filename); break; // Mime type not found default: throw new Exception("File is not an image, please use another file type.", 1); } $this->origWidth = imagesx($this->image); $this->origHeight = imagesy($this->image); } Resize The Image The resize function is what we will use to calculate the new values for the image width and height. This takes 3 parameters the new width, new height and the resize option, this will allow us to resize the image to exact dimensions, use the defined width with the height and keep aspect ratio, use the define height keeping the aspect ratio or let the class decide the best way of resizing the image. Once we have the new width and height of the image we can create a new image resource by using the PHP function imagecreatetruecolor(). Now we can create the new image from the old image resizing it to the new dimensions by using the imagecopyresampled() function. /** * Resize the image to these set dimensions * * @param int $width - Max width of the image * @param int $height - Max height of the image * @param string $resizeOption - Scale option for the image * * @return Save new image */ public function resizeTo( $width, $height, $resizeOption = 'default' ) { switch(strtolower($resizeOption)) { case 'exact': $this->resizeWidth = $width; $this->resizeHeight = $height; break; case 'maxwidth': $this->resizeWidth = $width; $this->resizeHeight = $this->resizeHeightByWidth($width); break; case 'maxheight': $this->resizeWidth = $this->resizeWidthByHeight($height); $this->resizeHeight = $height; break; default: if($this->origWidth > $width || $this->origHeight > $height) { if ( $this->origWidth > $this->origHeight ) { $this->resizeHeight = $this->resizeHeightByWidth($width); $this->resizeWidth = $width; } else if( $this->origWidth < $this->origHeight ) { $this->resizeWidth = $this->resizeWidthByHeight($height); $this->resizeHeight = $height; } } else { $this->resizeWidth = $width; $this->resizeHeight = $height; } break; } $this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight); imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight); } /** * Get the resized height from the width keeping the aspect ratio * * @param int $width - Max image width * * @return Height keeping aspect ratio */ private function resizeHeightByWidth($width) { return floor(($this->origHeight / $this->origWidth) * $width); } /** * Get the resized width from the height keeping the aspect ratio * * @param int $height - Max image height * * @return Width keeping aspect ratio */ private function resizeWidthByHeight($height) { return floor(($this->origWidth / $this->origHeight) * $height); } Save The Image With the new image now set in a class variable we can now use this to save the image on the server. This function will take 3 parameters the save path, the image quality and if we want to download the image. For each mime type PHP has a function imagejpeg(), imagegif(), imagepng() that will allow you to save the image by passing in the new image resource and the path the image is going to be saved. Once this image is saved on the server and we decided to download it we can change the headers to allow the browser to download the image on the clients machine. /** * Save the image as the image type the original image was * * @param String[type] $savePath - The path to store the new image * @param string $imageQuality - The qulaity level of image to create * * @return Saves the image */ public function saveImage($savePath, $imageQuality="100", $download = false) { switch($this->ext) { case 'image/jpg': case 'image/jpeg': // Check PHP supports this file type if (imagetypes() & IMG_JPG) { imagejpeg($this->newImage, $savePath, $imageQuality); } break; case 'image/gif': // Check PHP supports this file type if (imagetypes() & IMG_GIF) { imagegif($this->newImage, $savePath); } break; case 'image/png': $invertScaleQuality = 9 - round(($imageQuality/100) * 9); // Check PHP supports this file type if (imagetypes() & IMG_PNG) { imagepng($this->newImage, $savePath, $invertScaleQuality); } break; } if($download) { header('Content-Description: File Transfer'); header("Content-type: application/octet-stream"); header("Content-disposition: attachment; filename= ".$savePath.""); readfile($savePath); } imagedestroy($this->newImage); } Full Resize Image Class setImage( $filename ); } else { throw new Exception('Image ' . $filename . ' can not be found, try another image.'); } } /** * Set the image variable by using image create * * @param string $filename - The image filename */ private function setImage( $filename ) { $size = getimagesize($filename); $this->ext = $size['mime']; switch($this->ext) { // Image is a JPG case 'image/jpg': case 'image/jpeg': // create a jpeg extension $this->image = imagecreatefromjpeg($filename); break; // Image is a GIF case 'image/gif': $this->image = @imagecreatefromgif($filename); break; // Image is a PNG case 'image/png': $this->image = @imagecreatefrompng($filename); break; // Mime type not found default: throw new Exception("File is not an image, please use another file type.", 1); } $this->origWidth = imagesx($this->image); $this->origHeight = imagesy($this->image); } /** * Save the image as the image type the original image was * * @param String[type] $savePath - The path to store the new image * @param string $imageQuality - The qulaity level of image to create * * @return Saves the image */ public function saveImage($savePath, $imageQuality="100", $download = false) { switch($this->ext) { case 'image/jpg': case 'image/jpeg': // Check PHP supports this file type if (imagetypes() & IMG_JPG) { imagejpeg($this->newImage, $savePath, $imageQuality); } break; case 'image/gif': // Check PHP supports this file type if (imagetypes() & IMG_GIF) { imagegif($this->newImage, $savePath); } break; case 'image/png': $invertScaleQuality = 9 - round(($imageQuality/100) * 9); // Check PHP supports this file type if (imagetypes() & IMG_PNG) { imagepng($this->newImage, $savePath, $invertScaleQuality); } break; } if($download) { header('Content-Description: File Transfer'); header("Content-type: application/octet-stream"); header("Content-disposition: attachment; filename= ".$savePath.""); readfile($savePath); } imagedestroy($this->newImage); } /** * Resize the image to these set dimensions * * @param int $width - Max width of the image * @param int $height - Max height of the image * @param string $resizeOption - Scale option for the image * * @return Save new image */ public function resizeTo( $width, $height, $resizeOption = 'default' ) { switch(strtolower($resizeOption)) { case 'exact': $this->resizeWidth = $width; $this->resizeHeight = $height; break; case 'maxwidth': $this->resizeWidth = $width; $this->resizeHeight = $this->resizeHeightByWidth($width); break; case 'maxheight': $this->resizeWidth = $this->resizeWidthByHeight($height); $this->resizeHeight = $height; break; default: if($this->origWidth > $width || $this->origHeight > $height) { if ( $this->origWidth > $this->origHeight ) { $this->resizeHeight = $this->resizeHeightByWidth($width); $this->resizeWidth = $width; } else if( $this->origWidth < $this->origHeight ) { $this->resizeWidth = $this->resizeWidthByHeight($height); $this->resizeHeight = $height; } } else { $this->resizeWidth = $width; $this->resizeHeight = $height; } break; } $this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight); imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight); } /** * Get the resized height from the width keeping the aspect ratio * * @param int $width - Max image width * * @return Height keeping aspect ratio */ private function resizeHeightByWidth($width) { return floor(($this->origHeight/$this->origWidth)*$width); } /** * Get the resized width from the height keeping the aspect ratio * * @param int $height - Max image height * * @return Width keeping aspect ratio */ private function resizeWidthByHeight($height) { return floor(($this->origWidth/$this->origHeight)*$height); } } ?> Using The Resize Image PHP Class Because we have created this to allow you to resize the image in multiple ways it means that there are different ways of using the class. Resize the image to an exact size. Resize the image to a max width size keeping aspect ratio of the image. Resize the image to a max height size keeping aspect ratio of the image. Resize the image to a given width and height and allow the code to work out which way of resizing is best keeping the aspect ratio. You can save the created resize image on the server. You can download the created resize image on the server. Resize Exact Size To resize an image to an exact size you can use the following code. First pass in the image we want to resize in the class constructor, then define the width and height with the scale option of exact. The class will now have the create dimensions to create the new image, now call the function saveImage() and pass in the new file location to the new image. $resize = new ResizeImage('images/Be-Original.jpg'); $resize->resizeTo(100, 100, 'exact'); $resize->saveImage('images/be-original-exact.jpg'); Resize Max Width Size If you choose to set the image to be an exact size then when the image is resized it could lose it's aspect ratio, which means the image could look stretched. But if you know the max width that you want the image to be you can resize the image to a max width, this will keep the aspect ratio of the image. $resize = new ResizeImage('images/Be-Original.jpg'); $resize->resizeTo(100, 100, 'maxWidth'); $resize->saveImage('images/be-original-maxWidth.jpg'); Resize Max Height Size Just as you can select a max width for the image while keeping aspect ratio you can also select a max height while keeping aspect ratio. $resize = new ResizeImage('images/Be-Original.jpg'); $resize->resizeTo(100, 100, 'maxHeight'); $resize->saveImage('images/be-original-maxHeight.jpg'); Resize Auto Size From Given Width And Height You can also allow the code to work out the best way to resize the image, so if the image height is larger than the width then it will resize the image by using the height and keeping aspect ratio. If the image width is larger than the height then the image will be resized using the width and keeping the aspect ratio. $resize = new ResizeImage('images/Be-Original.jpg'); $resize->resizeTo(100, 100); $resize->saveImage('images/be-original-default.jpg'); Download The Resized Image The default behaviour for this class is to save the image on the server, but you can easily change this to download by passing in a true parameter to the saveImage method. $resize = new ResizeImage('images/Be-Original.jpg'); $resize->resizeTo(100, 100, 'exact'); $resize->saveImage('images/be-original-exact.jpg', "100", true);
May 21, 2013
Β· 80,105 Views
Absolute Center Images With CSS
Here is a technique about how you can absolute center position an element on the horizontal and vertical in CSS. Center Images Horizontally To center something on the horizontal in CSS it's quite easy all you need to do is set the width on the element and apply an auto margin-left and margin-right on to the image. The browser will work out the exact margin on both the right and left side of the image. This will position the image in the center of the parent element just by using the width and the margin properties. img { width:250px; margin: 0 auto; } Center Images On Horizontal and Vertical Setting the image to be center on the horizontal is easy you just need to set an auto on the left and right margin. But to set the image on the vertical and on the horizontal you need to set the margin on the top and left of the element. The following technique is something you can use to display a pop-up window to show an image gallery in the center of the screen. This example will center the image with a width of 250px, first to set the image to be absolute positioned and set the top and left property to be 50%. This will position the image in the middle of screen, but the image won't be exactly center. img { height: 250px; left: 50%; position: absolute; top: 50%; width: 250px; } The top left corner of the image will be the exact center of the screen, to move this point to the center of the image we need to move the image half it's width and half it's height. To move the image on half it's width and half it's height you need to add a margin-top which is negative half the height of the image and a margin-left which is negative half the width of the image. img { height: 250px; left: 50%; margin-top: -125px; margin-left: -125px; position: absolute; top: 50%; width: 250px; }
May 8, 2013
Β· 60,269 Views
Validate Featured Image On Post
Since WordPress version 2.9 you have been able to add a post thumbnail to all your posts on your website. A post thumbnail is called a featured image for the posts, this image can be displayed in anyway you want, it is up to the theme developer. The benefit of this image is that it allows you to add an image to a post without it appearing in the content of the actual post. This will allow you to use an image to display the post instead of just the content. The main use of this image is to be used on the index page or the search results page of your WordPress site. Enable Theme Support For Featured Post By default themes do not support this feature you need to add some code to the functiona.php file. add_theme_support( 'post-thumbnails' ); Set Featured Image There is a meta box on the post screen where you can set an image to be the featured image on the post. Display The Featured Image To display the featured image on your WordPress theme you need to use the function the_post_thumbnail(), but first you need to check if the post currently has a thumbnail image by using the has_post_thumbnail(). if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it. the_post_thumbnail(); } Validate Featured Image On Post If you theme requires that a post has a featured image then you need to make sure that your post has a featured image before you allow your users to publish the post. If you need to validate a post you can do this on the saving the post action save_post, this action will be ran when you save the current post. For us to validate this correctly we need to to check if the post has a post thumbnail by using the has_post_thumbnail() function. If the post doesn't have a post thumbnail then we need to set the post back to be a draft status and display an error message on the screen. Validate Post Thumbnail The following code can be used to validate the post thumbnail. This code will run on the save action of the post, first we check that the post type is for a post. If the post type is not a post then we return from the function so we don't continue. Then we check to see if the post has a thumbnail if it doesn't have a thumbnail then we set a new transient so that we can display an error message. Then we reset the post status to draft so the post doesn't displayed on the website. If the post has a thumbnail then we can just delete the transient so the error message isn't displayed anymore. add_action('save_post', 'pu_validate_thumbnail'); function pu_validate_thumbnail($post_id) { // Only validate post type of post if(get_post_type($post_id) != 'post') return; // Check post has a thumbnail if ( !has_post_thumbnail( $post_id ) ) { // Confirm validate thumbnail has failed set_transient( "pu_validate_thumbnail_failed", "true" ); // Remove this action so we can resave the post as a draft and then reattach the post remove_action('save_post', 'pu_validate_thumbnail'); wp_update_post(array('ID' => $post_id, 'post_status' => 'draft')); add_action('save_post', 'pu_validate_thumbnail'); } else { // If the post has a thumbnail delete the transient delete_transient( "pu_validate_thumbnail_failed" ); } } Next we use the admin_notices action to display an error message if the transient is set. Once the message is displayed then we can delete the transient. add_action('admin_notices', 'pu_validate_thumbnail_error'); function pu_validate_thumbnail_error() { // check if the transient is set, and display the error message if ( get_transient( "pu_validate_thumbnail_failed" ) == "true" ) { echo " A post thumbnail must be set before saving the post. "; delete_transient( "pu_validate_thumbnail_failed" ); } } When you save the post and it doesn't have a featured image then you will see the post is set back to a draft and an error message is displayed on the screen.
May 7, 2013
Β· 5,783 Views
Disable Scroll Wheel Zoom On Google Maps
Trying to disable scroll wheel zoom in Google maps.
May 3, 2013
Β· 30,863 Views
Always Get A Checkbox $_POST Value
The problem with checkboxes is that if they are not checked then they are not posted with your form. If you check a checkbox and post a form you will get the value of the checkbox in the $_POST variable which you can use to process a form, if it's unchecked no value will be added to the $_POST variable. In PHP you would normally get around this problem by doing an isset() check on your checkbox element. If the element you are expecting isn't set in the $_POST variable then we know that the checkbox is not checked and the value can be false. if(!isset($_POST['checkbox1'])) { $checkboxValue = false; } else { $checkboxValue = $_POST['checkbox1']; } But if you have created a dynamic form then you won't always know the name attribute of your checkboxes, if you don't know the name of the checkbox then you can't use the isset function to check if this has been sent with the $_POST variable. To get around this problem you can use a new hidden element which will store the true value of the checkbox. What you need to do is create a hidden element and use Javascript to change the value of the hidden field to the true value of the checkbox. If you don't set a value of the checkbox then when the checkbox is checked and the form is submitted the value will come through as on. You can change this by setting the value attribute on your checkbox. But because there is no unchecked value we won't know if this checkbox isn't checked. This is where the hidden element will be useful. When we submit these elements we will now always get the hidden element checkbox1 but may or may not get the element checkbox1_checked depending on if the checkbox is checked. The problem we have now is that we need to find a way of changing the value in the hidden field once the checkbox has been clicked, which can be done with the following Javascript. $('input[type="checkbox"]').on('change', function(e){ if($(this).prop('checked')) { $(this).next().val(1); } else { $(this).next().val(0); } }); This Javascript will be applied to all checkboxes, on the click event of each checkbox we see if the checkbox is currently checked. If it is checked then we get the next element (which should be the hidden field) and change the value to our checked value. If the checkbox is not checked then we get the hidden field and change the value to the unchecked state. Now when we post the form we will always get the true checkbox value even if the checkbox isn't checked. This will allow us to create a dynamic form with checkboxes and know if they have been checked or unchecked.
May 2, 2013
Β· 32,072 Views
Display A List Of Authors On WordPress
On some blogs it is important to post on a regular basis, but this can be difficult unless blogging is your full time job. For a single person to regularly post awesome blog posts everyday can take up a lot of time. For this reason many blogs have a number of authors, this helps keep the content regular and high quality to ensure a better blog. On a single author blog you will normally find an about page that will tell you information about the author. You can do this on a multi author blog but you also need to create a page that will display all the authors on the blog so you can link to each of their posts. If you want to create a page to display all the authors you have two options, you can create a new page template which will allow you to code the layout of the page to show all the authors. The other option is to create a shortcode where the user of the site can use this on a new page content to create a list of all the authors. The two options should be decided on if you are going to add this functionality in a plugin or a theme. If you are going to add this functionality to the theme then you should use a page template, if you want to use the shortcode then you should do this with a plugin. In this tutorial we are going to create a page template to display all the authors on the site. Create A Page Template First start off by creating a new page template for your list of all authors. /* Template Name: Display All Authors */ The next thing we need to do is get a list of all users on the WordPress site that could write a post. This is all the users apart from the users with the subscriber role, the best way of getting a list of all users is to use the function get_users(). This will return an array of all users on your site, it takes a number of different parameters such as: blog_id - The current blog's ID, unless multisite is enabled and another ID is provided role - Limit the returned authors to the role specified. include - An array of IDs. Only users matching these IDs will be returned. exclude - An array of IDs. Users matching these IDs will not be returned, regardless of the other arguments. meta_key - The meta_key in the wp_usermeta table for the meta_value to be returned. meta_value - The value of the meta key. meta_compare - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or '<='. Default value is '='. meta_query - A WP_Query style multiple meta_key/meta_value array. orderby - Sort by 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display_name', or 'post_count'. order - ASC (ascending) or DESC (descending). offset - The first n users to be skipped in the returned array. search - Use this argument to search users by email address, URL, ID or username (this does not currently include display name). number - Limit the total number of users returned. count_total - False by default. fields - Which fields to include in the returned array. Default is "all". If set to 'all_with_meta', returns an array of WP_User objects keyed by ID. who - If set to 'authors', only authors (user level greater than 0) will be returned. The parameters that we are going to be using is the orderby and order parameters. This is because we are going to use the orderby parameter to display the authors in order of the amount of posts they have wrote. Then we are going to use the order parameter to order the users is DESC order to display the the user with the most posts first. The other parameter that we could use is the role parameter to bring a back users with a specific role, or we can leave this blank to bring back all users. For this author list we want to display all users except for users with the subscriber role, so we are going to leave this blank and return all users. $allUsers = get_users('orderby=post_count&order=DESC'); As we have all the users we need to filter these and remove the users with the subscriber role, this can easily be done by looping through all the users, checking their role and creating a new array for user's which are not subscribers. $users = array(); // Remove subscribers from the list as they won't write any articles foreach($allUsers as $currentUser) { if(!in_array( 'subscriber', $currentUser->roles )) { $users[] = $currentUser; } } Now we have a new $users array which is populated with all users which are not subscribers, we can now loop through this array to display each user on the page. The user information we are going to display is the user name, user image, a link to all their posts, author description and links to add author meta information. Display Author Avatar To display the author avatar we can use the author email with the function get_avatar() to display the author avatar. user_email, '128' ); ?> Display Author Name To display the author name we can use a property value on the user object we are looping through by using $user->display_name; display_name; ?> Display Author Description To display the author description we can use the function get_user_meta() to get the author description. ID, 'description', true); ?> Link To All Author Posts To display a link to all the author posts you can use the function get_author_posts_url(). View Author Links Display Other User Meta Information You can assign new contact information to your users which you can display on the author list by using the function get_user_meta(). In this tutorial we are using this function to display links to the user different social media profiles. user_url; if($user->user_url != '') { printf(' %s ', $user->user_url, 'Website'); } $twitter = get_user_meta($user->ID, 'twitter_profile', true); if($twitter != '') { printf(' %s ', $twitter, 'Twitter'); } $facebook = get_user_meta($user->ID, 'facebook_profile', true); if($facebook != '') { printf(' %s ', $facebook, 'Facebook'); } $google = get_user_meta($user->ID, 'google_profile', true); if($google != '') { printf(' %s ', $google, 'Google'); } $linkedin = get_user_meta($user->ID, 'linkedin_profile', true); if($linkedin != '') { printf(' %s ', $linkedin, 'LinkedIn'); } ?> By putting the above code inside the loop you can display all the information you need to show your visitors all about the authors of your blog. Full Page Template Here is the full page template you can use on theme. roles )) { $users[] = $currentUser; } } ?> %s ', the_title()); foreach($users as $user) { ?> user_email, '128' ); ?> display_name; ?> ID, 'description', true); ?> View Author Links user_url; if($user->user_url != '') { printf(' %s ', $user->user_url, 'Website'); } $twitter = get_user_meta($user->ID, 'twitter_profile', true); if($twitter != '') { printf(' %s ', $twitter, 'Twitter'); } $facebook = get_user_meta($user->ID, 'facebook_profile', true); if($facebook != '') { printf(' %s ', $facebook, 'Facebook'); } $google = get_user_meta($user->ID, 'google_profile', true); if($google != '') { printf(' %s ', $google, 'Google'); } $linkedin = get_user_meta($user->ID, 'linkedin_profile', true); if($linkedin != '') { printf(' %s ', $linkedin, 'LinkedIn'); } ?>
April 30, 2013
Β· 11,596 Views
Add Custom Post Meta Data To Post List Table
One of the best thing about WordPress is that you can customise almost anything. In the admin area you can see a list of all the posts you have added in WordPress. Within this table it shows the basic information for each of the posts, the title, the author, the category, tags, comments and the date the post was published. WordPress has a number of different filters and actions that allow you to edit the output of the column so you can add your own data to this list. For example if you have custom post meta data which is useful information you want to display on the list of posts you can add new custom columns to the list. In this article you will learn how to add new columns to the post list, how you can add data to the column and how you can make this column sortable. Add New Columns First we start off by adding the new column to the list, for this we use the WordPress filter manage_edit-post_columns. This will allow you to edit the output of the columns by adding new values to the column array. The callback function on this filter will pass in one parameter which are the current columns on the list, the return of this function will be the new columns on the post table. This means that we can add additional values to the array to add extra columns to the table. The following code will add a new column to the table just after the title column. // Add a column to the edit post list add_filter( 'manage_edit-post_columns', 'add_new_columns'); /** * Add new columns to the post table * * @param Array $columns - Current columns on the list post */ function add_new_columns( $columns ) { $column_meta = array( 'meta' => 'Custom Column' ); $columns = array_slice( $columns, 0, 2, true ) + $column_meta + array_slice( $columns, 2, NULL, true ); return $columns; } Add Columns To Custom Post Types If you have custom post types in your site and want to add additional columns to this list, WordPress comes with built in filters you can apply to add new columns to this table. add_filter( 'manage_${post_type}_posts_columns', 'add_new_columns'); If you have a custom post type of portfolio then you can use the following code to add a column to the list of portfolio post types. function add_portfolio_columns($columns) { return array_merge($columns, array('client' => __('Client'), 'project_date' =>__( 'Project Date'))); } add_filter('manage_portfolio_posts_columns' , 'add_portfolio_columns'); Add Data To Custom Columns Once you have created the new columns for the posts list you can now add data to the new columns by using the WordPress action manage_posts_custom_column. Adding an action to this will be called on each column, from this call we can get data for the post display this on the post list. The following code will check what column we are on and get the custom post meta data for the current post and display this in the column. // Add action to the manage post column to display the data add_action( 'manage_posts_custom_column' , 'custom_columns' ); /** * Display data in new columns * * @param $column Current column * * @return Data for the column */ function custom_columns( $column ) { global $post; switch ( $column ) { case 'meta': $metaData = get_post_meta( $post->ID, 'twitter_url', true ); echo $metaData; break; } } Add Data To Custom Post Type Columns Along with being able to add a filter to custom post types by adding new columns, WordPress has a built in action you can use to add data to custom columns. In the above example we add a new column just for post types of a portfolio to add two new columns to the list, using the below code you can add data to these new columns. function custom_portfolio_column( $column, $post_id ) { switch ( $column ) { case 'project_date': echo get_post_meta( $post_id , 'project_date' , true ); break; case 'client': echo get_post_meta( $post_id , 'client' , true ); break; } } add_action( 'manage_portfolio_posts_custom_column' , 'custom_portfolio_column' ); Make Columns Sortable By default the new custom columns are not sortable so this makes it hard to find data that you need. To sort the custom columns WordPress has another filter manage_edit-post_sortable_columns you can use to assign which columns are sortable. When this action is ran the function will pass in a parameter of all the columns which are currently sortable, by adding your new custom columns to this list will now make these columns sortable. The value you give this will be used in the URL so WordPress understands which column to order by. The following to allow you to sort by the custom column meta. // Register the column as sortable function register_sortable_columns( $columns ) { $columns['meta'] = 'Custom Column'; return $columns; } add_filter( 'manage_edit-post_sortable_columns', 'register_sortable_columns' ); That's all the information you need to change the way posts are listed in your admin area. What useful information do you wish was displayed in the post list?
April 10, 2013
Β· 13,653 Views

User has been successfully modified

Failed to modify user

Let's be friends: