wordpress custom post type fugue icons

<?php
add_action( 'admin_head', 'cpt_icons' );
function cpt_icons() {
    ?>
    <style type="text/css" media="screen">
        #menu-posts-POSTTYPE .wp-menu-image {
            background: url(<?php bloginfo('template_url') ?>/images/YOURIMAGE.png) no-repeat 6px -17px !important;
        }
	#menu-posts-POSTTYPE:hover .wp-menu-image, #menu-posts-POSTTYPE.wp-has-current-submenu .wp-menu-image {
            background-position:6px 7px!important;
        }
    </style>
<?php } ?

 

Useful PHP Functions and Features You Need to Know

Even after using PHP for years, we stumble upon functions and features that we did not know about. Some of these can be quite useful, yet underused. With that in mind, I’ve compiled a list of nine incredibly useful PHP functions and features that you should be familiar with.

 


1. Functions with Arbitrary Number of Arguments

You may already know that PHP allows you to define functions with optional arguments. But there is also a method for allowing completely arbitrary number of function arguments.

First, here is an example with just optional arguments:

  1. // function with 2 optional arguments
  2. function foo($arg1 = ”, $arg2 = ”) {
  3. echo “arg1: $arg1\n”;
  4. echo “arg2: $arg2\n”;
  5. }
  6. foo(‘hello’,’world’);
  7. /* prints:
  8. arg1: hello
  9. arg2: world
  10. */
  11. foo();
  12. /* prints:
  13. arg1:
  14. arg2:
  15. */

Now, let’s see how we can build a function that accepts any number of arguments. This time we are going to utilize func_get_args():

  1. // yes, the argument list can be empty
  2. function foo() {
  3. // returns an array of all passed arguments
  4. $args = func_get_args();
  5. foreach ($args as $k => $v) {
  6. echo “arg”.($k+1).”: $v\n”;
  7. }
  8. }
  9. foo();
  10. /* prints nothing */
  11. foo(‘hello’);
  12. /* prints
  13. arg1: hello
  14. */
  15. foo(‘hello’, ‘world’, ‘again’);
  16. /* prints
  17. arg1: hello
  18. arg2: world
  19. arg3: again
  20. */

2. Using Glob() to Find Files

Many PHP functions have long and descriptive names. However it may be hard to tell what a function namedglob() does unless you are already familiar with that term from elsewhere.

Think of it like a more capable version of the scandir() function. It can let you search for files by using patterns.

  1. // get all php files
  2. $files = glob(‘*.php’);
  3. print_r($files);
  4. /* output looks like:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. )
  12. */

You can fetch multiple file types like this:

  1. // get all php files AND txt files
  2. $files = glob(‘*.{php,txt}’, GLOB_BRACE);
  3. print_r($files);
  4. /* output looks like:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. [4] => log.txt
  12. [5] => test.txt
  13. )
  14. */

Note that the files can actually be returned with a path, depending on your query:

  1. $files = glob(‘../images/a*.jpg’);
  2. print_r($files);
  3. /* output looks like:
  4. Array
  5. (
  6. [0] => ../images/apple.jpg
  7. [1] => ../images/art.jpg
  8. )
  9. */

If you want to get the full path to each file, you can just call the realpath() function on the returned values:

  1. $files = glob(‘../images/a*.jpg’);
  2. // applies the function to each array element
  3. $files = array_map(‘realpath’,$files);
  4. print_r($files);
  5. /* output looks like:
  6. Array
  7. (
  8. [0] => C:\wamp\www\images\apple.jpg
  9. [1] => C:\wamp\www\images\art.jpg
  10. )
  11. */

3. Memory Usage Information

By observing the memory usage of your scripts, you may be able optimize your code better.

PHP has a garbage collector and a pretty complex memory manager. The amount of memory being used by your script. can go up and down during the execution of a script. To get the current memory usage, we can use the memory_get_usage() function, and to get the highest amount of memory used at any point, we can use the memory_get_peak_usage() function.

  1. echo “Initial: “.memory_get_usage().” bytes \n”;
  2. /* prints
  3. Initial: 361400 bytes
  4. */
  5. // let’s use up some memory
  6. for ($i = 0; $i < 100000; $i++) {
  7. $array []= md5($i);
  8. }
  9. // let’s remove half of the array
  10. for ($i = 0; $i < 100000; $i++) {
  11. unset($array[$i]);
  12. }
  13. echo “Final: “.memory_get_usage().” bytes \n”;
  14. /* prints
  15. Final: 885912 bytes
  16. */
  17. echo “Peak: “.memory_get_peak_usage().” bytes \n”;
  18. /* prints
  19. Peak: 13687072 bytes
  20. */

4. CPU Usage Information

For this, we are going to utilize the getrusage() function. Keep in mind that this is not available on Windows platforms.

  1. print_r(getrusage());
  2. /* prints
  3. Array
  4. (
  5. [ru_oublock] => 0
  6. [ru_inblock] => 0
  7. [ru_msgsnd] => 2
  8. [ru_msgrcv] => 3
  9. [ru_maxrss] => 12692
  10. [ru_ixrss] => 764
  11. [ru_idrss] => 3864
  12. [ru_minflt] => 94
  13. [ru_majflt] => 0
  14. [ru_nsignals] => 1
  15. [ru_nvcsw] => 67
  16. [ru_nivcsw] => 4
  17. [ru_nswap] => 0
  18. [ru_utime.tv_usec] => 0
  19. [ru_utime.tv_sec] => 0
  20. [ru_stime.tv_usec] => 6269
  21. [ru_stime.tv_sec] => 0
  22. )
  23. */

That may look a bit cryptic unless you already have a system administration background. Here is the explanation of each value (you don’t need to memorize these):

  • ru_oublock: block output operations
  • ru_inblock: block input operations
  • ru_msgsnd: messages sent
  • ru_msgrcv: messages received
  • ru_maxrss: maximum resident set size
  • ru_ixrss: integral shared memory size
  • ru_idrss: integral unshared data size
  • ru_minflt: page reclaims
  • ru_majflt: page faults
  • ru_nsignals: signals received
  • ru_nvcsw: voluntary context switches
  • ru_nivcsw: involuntary context switches
  • ru_nswap: swaps
  • ru_utime.tv_usec: user time used (microseconds)
  • ru_utime.tv_sec: user time used (seconds)
  • ru_stime.tv_usec: system time used (microseconds)
  • ru_stime.tv_sec: system time used (seconds)

To see how much CPU power the script has consumed, we need to look at the ‘user time’ and ‘system time’ values. The seconds and microseconds portions are provided separately by default. You can divide the microseconds value by 1 million, and add it to the seconds value, to get the total seconds as a decimal number.

Let’s see an example:

  1. // sleep for 3 seconds (non-busy)
  2. sleep(3);
  3. $data = getrusage();
  4. echo “User time: “.
  5. ($data[‘ru_utime.tv_sec’] +
  6. $data[‘ru_utime.tv_usec’] / 1000000);
  7. echo “System time: “.
  8. ($data[‘ru_stime.tv_sec’] +
  9. $data[‘ru_stime.tv_usec’] / 1000000);
  10. /* prints
  11. User time: 0.011552
  12. System time: 0
  13. */

Even though the script took about 3 seconds to run, the CPU usage was very very low. Because during the sleep operation, the script actually does not consume CPU resources. There are many other tasks that may take real time, but may not use CPU time, like waiting for disk operations. So as you see, the CPU usage and the actual length of the runtime are not always the same.

Here is another example:

  1. // loop 10 million times (busy)
  2. for($i=0;$i<10000000;$i++) {
  3. }
  4. $data = getrusage();
  5. echo “User time: “.
  6. ($data[‘ru_utime.tv_sec’] +
  7. $data[‘ru_utime.tv_usec’] / 1000000);
  8. echo “System time: “.
  9. ($data[‘ru_stime.tv_sec’] +
  10. $data[‘ru_stime.tv_usec’] / 1000000);
  11. /* prints
  12. User time: 1.424592
  13. System time: 0.004204
  14. */

That took about 1.4 seconds of CPU time, almost all of which was user time, since there were no system calls.

System Time is the amount of time the CPU spends performing system calls for the kernel on the program’s behalf. Here is an example of that:

  1. $start = microtime(true);
  2. // keep calling microtime for about 3 seconds
  3. while(microtime(true) – $start < 3) {
  4. }
  5. $data = getrusage();
  6. echo “User time: “.
  7. ($data[‘ru_utime.tv_sec’] +
  8. $data[‘ru_utime.tv_usec’] / 1000000);
  9. echo “System time: “.
  10. ($data[‘ru_stime.tv_sec’] +
  11. $data[‘ru_stime.tv_usec’] / 1000000);
  12. /* prints
  13. User time: 1.088171
  14. System time: 1.675315
  15. */

Now we have quite a bit of system time usage. This is because the script calls the microtime() function many times, which performs a request through the operating system to fetch the time.

 

Also you may notice the numbers do not quite add up to 3 seconds. This is because there were probably other processes on the server as well, and the script was not using 100% CPU for the whole duration of the 3 seconds.


5. Magic Constants

PHP provides useful magic constants for fetching the current line number (__LINE__), file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace (__NAMESPACE__).

We are not going to cover each one of these in this article, but I will show you a few use cases.

When including other scripts, it is a good idea to utilize the __FILE__ constant (or also __DIR__ , as of PHP 5.3):

  1. // this is relative to the loaded script’s path
  2. // it may cause problems when running scripts from different directories
  3. require_once(‘config/database.php’);
  4. // this is always relative to this file’s path
  5. // no matter where it was included from
  6. require_once(dirname(__FILE__) . ‘/config/database.php’);

Using __LINE__ makes debugging easier. You can track down the line numbers:

  1. // some code
  2. // …
  3. my_debug(“some debug message”, __LINE__);
  4. /* prints
  5. Line 4: some debug message
  6. */
  7. // some more code
  8. // …
  9. my_debug(“another debug message”, __LINE__);
  10. /* prints
  11. Line 11: another debug message
  12. */
  13. function my_debug($msg, $line) {
  14. echo “Line $line: $msg\n”;
  15. }

6. Generating Unique ID’s

There may be situations where you need to generate a unique string. I have seen many people use themd5() function for this, even though it’s not exactly meant for this purpose:

  1. // generate unique string
  2. echo md5(time() . mt_rand(1,1000000));

There is actually a PHP function named uniqid() that is meant to be used for this.

  1. // generate unique string
  2. echo uniqid();
  3. /* prints
  4. 4bd67c947233e
  5. */
  6. // generate another unique string
  7. echo uniqid();
  8. /* prints
  9. 4bd67c9472340
  10. */

You may notice that even though the strings are unique, they seem similar for the first several characters. This is because the generated string is related to the server time. This actually has a nice side effect, as every new generated id comes later in alphabetical order, so they can be sorted.

To reduce the chances of getting a duplicate, you can pass a prefix, or the second parameter to increase entropy:

  1. // with prefix
  2. echo uniqid(‘foo_’);
  3. /* prints
  4. foo_4bd67d6cd8b8f
  5. */
  6. // with more entropy
  7. echo uniqid(”,true);
  8. /* prints
  9. 4bd67d6cd8b926.12135106
  10. */
  11. // both
  12. echo uniqid(‘bar_’,true);
  13. /* prints
  14. bar_4bd67da367b650.43684647
  15. */

This function will generate shorter strings than md5(), which will also save you some space.


7. Serialization

Have you ever needed to store a complex variable in a database or a text file? You do not have to come up with a fancy solution to convert your arrays or objects into formatted strings, as PHP already has functions for this purpose.

There are two popular methods of serializing variables. Here is an example that uses the serialize() andunserialize():

  1. // a complex array
  2. $myvar = array(
  3. ‘hello’,
  4. 42,
  5. array(1,’two’),
  6. ‘apple’
  7. );
  8. // convert to a string
  9. $string = serialize($myvar);
  10. echo $string;
  11. /* prints
  12. a:4:{i:0;s:5:”hello”;i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:”two”;}i:3;s:5:”apple”;}
  13. */
  14. // you can reproduce the original variable
  15. $newvar = unserialize($string);
  16. print_r($newvar);
  17. /* prints
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */

This was the native PHP serialization method. However, since JSON has become so popular in recent years, they decided to add support for it in PHP 5.2. Now you can use the json_encode() and json_decode()functions as well:

  1. // a complex array
  2. $myvar = array(
  3. ‘hello’,
  4. 42,
  5. array(1,’two’),
  6. ‘apple’
  7. );
  8. // convert to a string
  9. $string = json_encode($myvar);
  10. echo $string;
  11. /* prints
  12. [“hello”,42,[1,”two”],”apple”]
  13. */
  14. // you can reproduce the original variable
  15. $newvar = json_decode($string);
  16. print_r($newvar);
  17. /* prints
  18. Array
  19. (
  20. [0] => hello
  21. [1] => 42
  22. [2] => Array
  23. (
  24. [0] => 1
  25. [1] => two
  26. )
  27. [3] => apple
  28. )
  29. */

It is more compact, and best of all, compatible with javascript and many other languages. However, for complex objects, some information may be lost.


8. Compressing Strings

When talking about compression, we usually think about files, such as ZIP archives. It is possible to compress long strings in PHP, without involving any archive files.

In the following example we are going to utilize the gzcompress() and gzuncompress() functions:

  1. $string =
  2. “Lorem ipsum dolor sit amet, consectetur
  3. adipiscing elit. Nunc ut elit id mi ultricies
  4. adipiscing. Nulla facilisi. Praesent pulvinar,
  5. sapien vel feugiat vestibulum, nulla dui pretium orci,
  6. non ultricies elit lacus quis ante. Lorem ipsum dolor
  7. sit amet, consectetur adipiscing elit. Aliquam
  8. pretium ullamcorper urna quis iaculis. Etiam ac massa
  9. sed turpis tempor luctus. Curabitur sed nibh eu elit
  10. mollis congue. Praesent ipsum diam, consectetur vitae
  11. ornare a, aliquam a nunc. In id magna pellentesque
  12. tellus posuere adipiscing. Sed non mi metus, at lacinia
  13. augue. Sed magna nisi, ornare in mollis in, mollis
  14. sed nunc. Etiam at justo in leo congue mollis.
  15. Nullam in neque eget metus hendrerit scelerisque
  16. eu non enim. Ut malesuada lacus eu nulla bibendum
  17. id euismod urna sodales. “;
  18. $compressed = gzcompress($string);
  19. echo “Original size: “. strlen($string).”\n”;
  20. /* prints
  21. Original size: 800
  22. */
  23. echo “Compressed size: “. strlen($compressed).”\n”;
  24. /* prints
  25. Compressed size: 418
  26. */
  27. // getting it back
  28. $original = gzuncompress($compressed);

We were able to achive almost 50% size reduction. Also the functions gzencode() and gzdecode() achive similar results, by using a different compression algorithm.


9. Register Shutdown Function

There is a function called register_shutdown_function(), which will let you execute some code right before the script finishes running.

Imagine that you want to capture some benchmark statistics at the end of your script execution, such as how long it took to run:

  1. // capture the start time
  2. $start_time = microtime(true);
  3. // do some stuff
  4. // …
  5. // display how long the script took
  6. echo “execution took: “.
  7. (microtime(true) – $start_time).
  8. ” seconds.”;

At first this may seem trivial. You just add the code to the very bottom of the script and it runs before it finishes. However, if you ever call the exit() function, that code will never run. Also, if there is a fatal error, or if the script is terminated by the user (by pressing the Stop button in the browser), again it may not run.

When you use register_shutdown_function(), your code will execute no matter why the script has stopped running:

  1. $start_time = microtime(true);
  2. register_shutdown_function(‘my_shutdown’);
  3. // do some stuff
  4. // …
  5. function my_shutdown() {
  6. global $start_time;
  7. echo “execution took: “.
  8. (microtime(true) – $start_time).
  9. ” seconds.”;
  10. }

Conclusion

Are you aware of any other PHP features that are not widely known but can be quite useful? Please share with us in the comments. And thank you for reading!

 

useful wp-config variables for WordPress

The majority of WordPress configuration settings are found, and are easily changed, from the WordPress admin panel. But did you know about the settings and options you can enable in the wp-config.php file? Lets run through some that we’ve found useful over time. To use them, place the code into your wp-config file which is found in the root of your WordPress install.

Debugging themes and plugins

To enable PHP error messages for testing you can use WP_DEBUG variable:

1
define('WP_DEBUG', true);

You will then see all PHP errors and notices and can debug accordingly. Remove it when your done; never leave this enabled in a production environment!

Increasing allocated WordPress memory

If you have a lot of plugins installed you may need to give WordPress more memory. Also, if you notice pages getting ‘cut off’ this may be a sign that you don’t have enough memory allocated to WordPress. By default, WordPress is allocated 32MB memory – increase it by adding the variable WP_MEMORY_LIMIT:

1
define('WP_MEMORY_LIMIT', '64MB');

Cleaning up the trash more often

When you delete a post in WordPress it goes into the ‘trash’ section – by default these are kept for 30 days. To change this, use EMPTY_TRASH_DAYS:

1
define('EMPTY_TRASH_DAYS', '60');

You can also set thus to 0 to disable the trash completely.

Disabling the file editor in Admin

Handing over a site to a client? You may not want them to use the built in theme/plugin editor in the backend since they could potentially break things; disable the editor by using:

1
define('DISALLOW_FILE_EDIT', true);

This can also help secure your site if someone evil gains access to a user account!

Changing the duration of Auto-save

You can change the duration at which WordPress auto-saves content – maybe you want it more often (if you make a lot of mistakes or forget to save normally), or perhaps you want to make it auto-save less often to reduce the load on the server. Simply use the AUTOSAVE_INTERVAL variable and set its value in seconds (default is 60 seconds):

1
define('AUTOSAVE_INTERVAL', 120);

Tweaking revisions

The revisions functionality of WordPress can be useful, but does make your database huge. You can tweak the amount of revisions kept by changing the WP_POST_REVISIONS variable:

1
define('WP_POST_REVISIONS', 2);

You can also set this to false to diable post revisions entirely.

Relocating a WordPress install

To move WordPress to a new URL you can use the RELOCATE variable:

1
define('RELOCATE', true);

After setting this, go to the wp-login.php page and then the URL’s will be updated

Managing Zend Framework Layouts ( change – enable – disable – set – Switching )

One immediate benefit developers stand to gain from adopting a framework such as the Zend Framework is a final resolution on managing website layouts and pages. Gone is the need to devise strategies for important tasks such as maintaining page headers and footers, separating the bulk of a page’s logic from its interface, and managing the code repeatedly used throughout the site to carry out special formatting actions. Instead, you can just embrace the framework’s conventions and move on to the next battle. This article introduces you to some of the fundamental concepts behind managing layouts within your Zend Framework-driven applications.

Managing Layouts

A website’s layout can be thought of as its template, which is to say the parts of the site design that generally do not change as the user navigates from one page to the next. Many PHP developers employ an approach involving managing page headers and footers in separate files and then using require() statements to assemble the page. While this approach may be fine for simple sites, it quickly becomes a burden as the site grows in complexity. The Zend Framework greatly improves upon this approach by utilizing a single template file (known as the layout), which is dynamically wrapped around the site’s pages.

Enabling Layout Management

Oddly, the Zend Framework’s layout feature isn’t enabled by default. To enable this feature you’ll need to navigate to your application’s home directory and use the Zend_Tool utility:
%>zf enable layout
Executing this command will create a directory named layouts within your project’s application directory, and within it, a file named layout.phtml. Open this file and you’ll see just a single line:
<?php echo $this->layout()->content; ?>
This line represents the location within the template where the content that makes up your site’s various pages (views) will be injected. Therefore, to add a header and footer to your site template all you need to do is code around this line, for instance:
<h1>Welcome to Acme, Inc.</h1>
<?php echo $this->layout()->content; ?>
<p>
Copyright &copy; 2010 Acme, Inc.
</p>

Switching Layouts

If you’d like to use an alternative layout for a particular view, copy the layout.phtml file and modify it to suit the design of your new template, before saving it under a new name within the layouts directory. Then within the controller action in which you’d like to use the new view, add this line:
$this->_helper_layout->setLayout('layout2');
Be sure to replace layout2 with the name of your new template. If you’d like to use this template in conjunction with all actions found in a specific controller, just place the above line in your controller’s init() method.

Disabling Layouts

If you’d like to disable a page’s layout and view altogether, use the following two lines to do so, respectively:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);

Using Layout Helpers

The Zend Framework is bundled with numerous helpers, which can be used to set and override layout attributes. For instance, if you were creating a web service that specified that JSON would be exclusively returned with each request, then within the controller you should set the content type to application/json. To do this all you need to do is return the JSON using the JSON helper:
echo $this->_helper->json($this->results);
Incidentally, the JSON helper will also automatically disable the layout and view for the action, saving you from having to execute the aforementioned disableLayout() and setNoRender() methods. Because most browsers do not recognize theapplication/json content type as a format that can be displayed within the browser, attempts to navigate to the URL associated with this action will cause the browser to prompt you for further instruction regarding what to do with the returned file. Of course, because the intent of such an action is to respond to AJAX requests, browser-specific behavior of this sort is irrelevant.
Many other native view helpers exist, consult the Zend Framework documentation for more information.

Conclusion

As I’ve mentioned many times within these pages, frameworks greatly improve developer productivity thanks to the “convention over configuration” paradigm. By reducing the number of decisions developers need to make in terms of implementation approach, additional time can logically be spent focusing on creating compelling features rather than, say, worrying about how to manage configuration data. Further, because the convention implementations make it easy (although not required) for the developer to employ widely accepted industry best practices such as database abstraction and data validation, framework adoption comes with the added bonus of producing more maintainable and secure code.
The Zend Framework offers users a great degree of layout flexibility, supporting the ability to create a global template, switch between multiple templates, override template defaults such as the document type, and even disable templates altogether. Do you have any useful layout-related tips or tricks? Tell us about them in the comments!

About the Author (copied post from this author thanks for this nice tut)

Jason Gilmore is the founder of EasyPHPWebsites.com and the author of several popular books, including “Easy PHP Web sites with the Zend Framework” and “Beginning PHP and MySQL: From Novice to Professional” (currently in its third edition). Check out his new DZone reference card, titled “Getting Started with the Zend Framework.”

Setting up Wildcard DNS for Subdomains on Cpanel

Ever wanted to setup subdomains on your Cpanel server, such that a keyword is the wildcard part of your domain? Something along the lines of:

  • keyword.yourdomain.com
  • keyword2.yourdomain.com
  • keyword3.yourdomain.com

It’s not as difficult as you might think, however, you will need access via SSH to edit a few server files, or, contact your web host to make a few quick edits on your account.

Continue reading “Setting up Wildcard DNS for Subdomains on Cpanel”

How to delete an entire directory via SSH

I know this is probably common knowledge to Linux and Unix but here it is
rm -r -f YourDirectory

rm = remove / delete
-r = recursively deletes the directory and all files in it, including subdirectories
-f = will not ask for confirmation before deleting

 

How to add the favicon to your page ?

  • Download favicon
  • Put the favicon.ico file into your webserver directory
  • This favicon is an animation. Internet Explorer doen’t support animated favicons yet. For that reason you need to generate an additional non-animated favicon.ico file.
  • Add the following lines between the <head> ... </head> tags of the page:

<link rel=”shortcut icon” href=”/PATH_TO_STATIC_FAVICON/favicon.ico” type=”image/x-icon”>

<link rel=”icon” href=”/PATH_TO_ANIMATED_FAVICON/favicon.ico” type=”image/x-icon”>

  • Replace PATH_TO_STATIC_FAVICON and PATH_TO_ANIMATED_FAVICON with the correct paths