most used wordpress functions in theme

In wordpress theming is very important. Developers know the importance of functions.php file. Here we given most used wordpress functions in theme which will be useful for wordpress developer. I always written some very nice code snippets in functions.php file.

most used wordpress functions in theme

I found very useful codes which is very helpful for very wordpress designer and developers.

Here is very useful code snippets.
Enable Hidden Admin Feature displaying ALL Site Settings

// CUSTOM ADMIN MENU LINK FOR ALL SETTINGS
   function all_settings_link() {
    add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
   }
   add_action('admin_menu', 'all_settings_link');

Remove Update Notification for all users except ADMIN User

// REMOVE THE WORDPRESS UPDATE NOTIFICATION FOR ALL USERS EXCEPT SYSADMIN
       global $user_login;
       get_currentuserinfo();
       if (!current_user_can('update_plugins')) { // checks to see if current user can update plugins
        add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
        add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
       }

Include custom post types in the search results.

// MAKE CUSTOM POST TYPES SEARCHABLE
function searchAll( $query ) {
 if ( $query->is_search ) { $query->set( 'post_type', array( 'site','plugin', 'theme','person' )); }
 return $query;
}
add_filter( 'the_search_query', 'searchAll' );

Add your custom post types to your sites main RSS feed by default.

// ADD CUSTOM POST TYPES TO THE DEFAULT RSS FEED
function custom_feed_request( $vars ) {
 if (isset($vars['feed']) && !isset($vars['post_type']))
  $vars['post_type'] = array( 'post', 'site', 'plugin', 'theme', 'person' );
 return $vars;
}
add_filter( 'request', 'custom_feed_request' );

Modify the Login Logo & Image URL Link

add_filter( 'login_headerurl', 'namespace_login_headerurl' );
/**
 * Replaces the login header logo URL
 *
 * @param $url
 */
function namespace_login_headerurl( $url ) {
    $url = home_url( '/' );
    return $url;
}

add_filter( 'login_headertitle', 'namespace_login_headertitle' );
/**
 * Replaces the login header logo title
 *
 * @param $title
 */
function namespace_login_headertitle( $title ) {
    $title = get_bloginfo( 'name' );
    return $title;
}

add_action( 'login_head', 'namespace_login_style' );
/**
 * Replaces the login header logo
 */
function namespace_login_style() {
    echo '<style>.login h1 a { background-image: url( ' . get_template_directory_uri() . '/images/logo.png ) !important; }</style>';
}

Loading jQuery from the Google CDN

// even more smart jquery inclusion :)
add_action( 'init', 'jquery_register' );

// register from google and for footer
function jquery_register() {

if ( !is_admin() ) {

    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', ( 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' ), false, null, true );
    wp_enqueue_script( 'jquery' );
}
}

Remove the WordPress Version Info for Security

// remove version info from head and feeds
function complete_version_removal() {
    return '';
}
add_filter('the_generator', 'complete_version_removal');

Add Spam & Delete Links to Comments on Front End

// spam & delete links for all versions of wordpress
function delete_comment_link($id) {
    if (current_user_can('edit_post')) {
        echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&c='.$id.'">del</a> ';
        echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&dt=spam&c='.$id.'">spam</a>';
    }
}

Remove Default WordPress Meta Boxes

// REMOVE META BOXES FROM DEFAULT POSTS SCREEN
   function remove_default_post_screen_metaboxes() {
 remove_meta_box( 'postcustom','post','normal' ); // Custom Fields Metabox
 remove_meta_box( 'postexcerpt','post','normal' ); // Excerpt Metabox
 remove_meta_box( 'commentstatusdiv','post','normal' ); // Comments Metabox
 remove_meta_box( 'trackbacksdiv','post','normal' ); // Talkback Metabox
 remove_meta_box( 'slugdiv','post','normal' ); // Slug Metabox
 remove_meta_box( 'authordiv','post','normal' ); // Author Metabox
 }
   add_action('admin_menu','remove_default_post_screen_metaboxes');

// REMOVE META BOXES FROM DEFAULT PAGES SCREEN
   function remove_default_page_screen_metaboxes() {
 remove_meta_box( 'postcustom','page','normal' ); // Custom Fields Metabox
 remove_meta_box( 'postexcerpt','page','normal' ); // Excerpt Metabox
 remove_meta_box( 'commentstatusdiv','page','normal' ); // Comments Metabox
 remove_meta_box( 'trackbacksdiv','page','normal' ); // Talkback Metabox
 remove_meta_box( 'slugdiv','page','normal' ); // Slug Metabox
 remove_meta_box( 'authordiv','page','normal' ); // Author Metabox
 }
   add_action('admin_menu','remove_default_page_screen_metaboxes');

Add Custom User Profile Fields

// CUSTOM USER PROFILE FIELDS
   function my_custom_userfields( $contactmethods ) {

    // ADD CONTACT CUSTOM FIELDS
    $contactmethods['contact_phone_office']     = 'Office Phone';
    $contactmethods['contact_phone_mobile']     = 'Mobile Phone';
    $contactmethods['contact_office_fax']       = 'Office Fax';

    // ADD ADDRESS CUSTOM FIELDS
    $contactmethods['address_line_1']       = 'Address Line 1';
    $contactmethods['address_line_2']       = 'Address Line 2 (optional)';
    $contactmethods['address_city']         = 'City';
    $contactmethods['address_state']        = 'State';
    $contactmethods['address_zipcode']      = 'Zipcode';
    return $contactmethods;
   }
   add_filter('user_contactmethods','my_custom_userfields',10,1);

Add an excerpt box for pages

if ( function_exists('add_post_type_support') )
{
    add_action('init', 'add_page_excerpts');
    function add_page_excerpts()
    {
        add_post_type_support( 'page', 'excerpt' );
    }
}

Function to change the length of Exerpt

function new_excerpt_length($length) {
    return 100;
}

add_filter('excerpt_length', 'new_excerpt_length');

Auto Extract the First Image from the Post Content

/ AUTOMATICALLY EXTRACT THE FIRST IMAGE FROM THE POST
function getImage($num) {
    global $more;
    $more = 1;
    $link = get_permalink();
    $content = get_the_content();
    $count = substr_count($content, '<img');
    $start = 0;
    for($i=1;$i<=$count;$i++) {
        $imgBeg = strpos($content, '<img', $start);
        $post = substr($content, $imgBeg);
        $imgEnd = strpos($post, '>');
        $postOutput = substr($post, 0, $imgEnd+1);
        $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
        $image[$i] = $postOutput;
        $start=$imgEnd+1;
    }
    if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
    $more = 0;
}

Unregister WP Default Widgets

// unregister all default WP Widgets
function unregister_default_wp_widgets() {
    unregister_widget('WP_Widget_Pages');
    unregister_widget('WP_Widget_Calendar');
    unregister_widget('WP_Widget_Archives');
    unregister_widget('WP_Widget_Links');
    unregister_widget('WP_Widget_Meta');
    unregister_widget('WP_Widget_Search');
    unregister_widget('WP_Widget_Text');
    unregister_widget('WP_Widget_Categories');
    unregister_widget('WP_Widget_Recent_Posts');
    unregister_widget('WP_Widget_Recent_Comments');
    unregister_widget('WP_Widget_RSS');
    unregister_widget('WP_Widget_Tag_Cloud');
}
add_action('widgets_init', 'unregister_default_wp_widgets', 1);

Enable GZIP output compression

if(extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler"))
   add_action('wp', create_function('', '@ob_end_clean();@ini_set("zlib.output_compression", 1);'));

Enable shortcodes in widgets

// shortcode in widgets
if ( !is_admin() ){
    add_filter('widget_text', 'do_shortcode', 11);
}

If you have any interesting code snippets then please suggest me.

most used wordpress functions in theme
most used wordpress functions in theme

install and update the wordpress plugins without providing ftp access

I did so much R&D about installing and updating the wordpress plugin without using ftp access. I got very nice trick to solve this issue. When you are using the shared hosting or VPS server for wordpress site hosting. You always face issue for installing the wordpress plugin or wordpress theme. It issue happen when you do the the wordpress updation. Using following simple steps you can install the wordpress plugins and themes without giving the ftp access.

update wordpress plugins without ftp access

I always did the wordpress plugins and theme updation. So every time providing the ftp credentials are really panic. So I am always using following steps for doing wordpress up-gradation.

First you need to add the following code in your wp-config.php file.

define('FTP_USER', 'username');
define('FTP_PASS', 'mypassword');
define('FTP_HOST', '192.168.2.132');
define('FTP_SSL', false);

But this is old idea. If you dont want to add the ftp access in wp-config.php file then Just add the following line wp-config.php file.


define('FS_METHOD', 'direct');

Note: You need to give 755 permission to wp-content folder. Create the upgrade folder in wp-content folder.

If still you are facing issue then give 777 permission to all wp-content folder.

For permission use following command

cd your_wordpress_directory
sudo chown -R www-data wp-content
sudo chmod -R 755 wp-content

More information:

WordPress will try to write a temporary file to your /wp-content directory. If this succeeds, it compares the ownership of the file with it’s own uid, and if there is a match it will allow you to use the ‘direct’ method of installing plugins, themes, or updates.

Now, if for some reason you do not want to rely on the automatic check for which filesystem method to use, you can define a constant, 'FS_METHOD' in your wp-config.php file that is either 'direct' 'ssh', 'ftpext' or 'ftpsockets' and it will use method. Keep in mind that if you set this to ‘direct’ but your web user (the username under which your webs server runs) does not have proper write permissions, you will receive an error.

update wordpress plugins without ftp access
update wordpress plugins without ftp access

implement jquery UI datepicker in wordpress

wordpress and jquery both are powerful tool. In plugin we need datepicker sometime. In this article i showed how to implement jquery UI datepicker in wordpress

implement jquery UI datepicker in wordpress

Some WP developers use the plugins to add the datepicker in wordpress. But you can add the Jquery datepicker in wordpress. How can use the Jquery UI in your wordpress theme and plugin using following code.  For adding the datepicker in theme you need to just add the following code in functions.php file.

[viral-lock message=”Some Source code is Hidden! It’s Visible for Users who Liked/Shared This article on Facebook or Twitter or Google+. Like or Tweet this article to reveal the content.”]


add_action( 'init', 'wpapi_date_picker' );
function wpapi_date_picker() {
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'jquery-ui-core' );
    wp_enqueue_script( 'jquery-datepicker', 'http://jquery-ui.googlecode.com/svn/trunk/ui/jquery.ui.datepicker.js', array('jquery', 'jquery-ui-core' ) );
}

add_action( 'wp_footer', 'wpapi_print_scripts');
function wpapi_print_scripts() {
    ?>
<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery('#datepicker').datepicker();
    })
</script>
    <!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php
}

[/viral-lock]

For showing the datepicker control in theme or plugin use following code.

<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery('#datepicker').datepicker({
        dateFormat : 'yy-mm-dd'
    });
});
</script>
implement jquery UI datepicker in wordpress
implement jquery UI datepicker in wordpress

If you have any issue for adding the datepicker control then please add comment or email me.

Show comments from custom post type in wordpress

WordPress tutorial, Show comments from custom post type in wordpress. we shows comments in sidebar. But what to do for show comments for custom post type.

Show comments from custom post type in wordpress

It’s not well documented, but according to the codex, you can pass a ‘post_type’ variable in the get_comments function.

<?php
 $comments = get_comments('number=10&status=approve&post_type=YOUR_POST_TYPE');
foreach($comments as $comment) :

// comment loop code will go here

endforeach;
?>

Note: This code only useful after wordpress 3.1 version.

Show comments from custom post type in wordpress
Show comments from custom post type in wordpress

Change image name to wordpress post slug during upload

WordPress tutorial, Change image name to wordpress post slug during upload. If you want to rename files during upload and set their names to the post slug.

If you want to rename files during upload and set their names to the post slug the files are being attached to, plus some random characters (a simple incremental counter will be just fine) to make the filenames different.

Change image name to wordpress post slug during upload

Change image name to wordpress post slug during upload
Change image name to wordpress post slug during upload

In other words, if you are uploading/attaching images to the post whose page slug is “test-page-slug”, i’d like for the images to be renamed on the fly to test-page-slug-[C].[original_extension] — test-page-slug-1.jpg, test-page-slug-2.jpg etc (no matter what the original filenames were).

This is very easy. You just need to use following hook in functions.php file.

function wp_modify_uploaded_file_names($image_name) {

    // Get the parent post ID, if there is one
    if( isset($_GET['post_id']) ) {
        $post_id = $_GET['post_id'];
    } elseif( isset($_POST['post_id']) ) {
        $post_id = $_POST['post_id'];
    }

    // Only do this if we got the post ID--otherwise they're probably in
    //  the media section rather than uploading an image from a post.
    if(is_numeric($post_id)) {

        // Get the post slug
        $post_obj = get_post($post_id);
        $post_slug = $post_obj->post_name;

        // If we found a slug
        if($post_slug) {

            $random_number = rand(10000,99999);
            $image_name['name'] = $post_slug . '-' . $random_number . '.jpg';

        }

    }

    return $image_name;

}
add_filter('wp_handle_upload_prefilter', 'wp_modify_uploaded_file_names', 1, 1);

This is very easy.
if you have pretty permalinks enabled, so I’ve added a check to make sure there is a slug before renaming the file. You’ll also want to consider checking the file type, which I haven’t done here–I’ve just assumed it’s a jpg.

Solved: qTranslate slug with Widget not working with pages

We just saw the issue with qtranslate slug with widget is not working for 0.5 version. URL is showing but URL is not opening and 404 page is opening. we solved  the of qTranslate slug with Widget not working with pages.

Solved issue qTranslate slug with Widget not working with pages

The problem was exactly at the function qTranslateSlug_filter_request inside de file qtranslate-slug-with-widget.php, which is the only one of the plugin, so it’s easy to find.
We must take a look at this part of the code:

if (isset($q['name'])) {
    $type = QTS_POST;
    $slug = $q['name'];
    $param = 'p';
    $get_link = 'get_permalink';
    unset($new_q['name']);
} else if (isset($q['pagename'])) {
    //$type = QTS_PAGE;
    //$slug = $q['pagename'];
    //$param = 'page_id';
    $id = qTranslateSlug_get_page_by_path($q['pagename'], $lang);
    if ($id) {
        unset($new_q['pagename']);
        $q = $new_q;
        $q['page_id'] = $id;
        $get_link = 'get_page_link';
    }
} else if (isset($q['category_name'])) {
    $type = QTS_CAT;
    $slug = $q['category_name'];
    $param = 'cat';
    $get_link = 'get_category_link';
    unset($new_q['category_name']);
} else if (isset($q['tag'])) {
    $type = QTS_TAG;
    $slug = $q['tag'];
    $param = 'tag_id';
    $get_link = 'get_tag_link';
    unset($new_q['tag']);
}

That we hace to replace with the following:

if (isset($q['name'])) {
        $id = qTranslateSlug_get_page_by_path($q['name'], $lang);
        if ($id) {
            unset($new_q['name']);
            $q = $new_q;
            $q['page_id'] = $id;
            $get_link = 'get_page_link';
        } else {
            $type = QTS_POST;
            $slug = $q['name'];
            $param = 'p';
            $get_link = 'get_permalink';
            unset($new_q['name']);
        }
    } else if (isset($q['pagename'])) {
        $id = qTranslateSlug_get_page_by_path($q['pagename'], $lang);
        if ($id) {
            unset($new_q['pagename']);
            $q = $new_q;
            $q['page_id'] = $id;
            $get_link = 'get_page_link';
        }
    } else if (isset($q['category_name'])) {
        $type = QTS_CAT;
        $slug = $q['category_name'];
        $param = 'cat';
        $get_link = 'get_category_link';
        unset($new_q['category_name']);
    } else if (isset($q['tag'])) {
        $type = QTS_TAG;
        $slug = $q['tag'];
        $param = 'tag_id';
        $get_link = 'get_tag_link';
        unset($new_q['tag']);
    } else {
        $path = trim(preg_replace('/\?(.*)/', '', $_SERVER['REQUEST_URI']), '/');
        $id = qTranslateSlug_get_page_by_path($path, $lang);
        if ($id) {
            if (isset ($q['attachment'])) {
                unset($q['attachment']);
                unset($new_q['attachment']);
            }
            $q = $new_q;
            $q['page_id'] = $id;
            $get_link = 'get_page_link';
        }
    }
Solved: qTranslate slug with Widget not working with pages
Solved: qTranslate slug with Widget not working with pages

With the last wordpress versions, mine is 3.3.1, has changed the way of passing the query to the request filter, changing the array slug position from ‘pagename’ to ‘name’, then the plugin didn’t have a way to find any page, since it expected to find in the array the position ‘pagename’, nonexistent for the current case.
Ref is taken from – http://en.codatavern.com/qtranslate-slug-with-widget-wordpress-plugin-fix/

how to integrate wordpress into php website

WordPress is very easy to work on. PHP tutorial, how to integrate wordpress into php website. you can very easily integrate the wordpress with php or html site. Here we given code for same.

There may be only a few features of WordPress you want to use when integrating it with your site, or you may want your entire site run with WordPress. This tutorial will guide you through making your WordPress site look like your current design.

how to integrate wordpress into php website

How to start?
First you need to disable the wordpress theme. using following code.

open your header.php file from your wordpress theme and put following code in that file.

<?php
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
?>

Create any php file and put following code in that file.

<?php
require('/the/path/to/your/wp-blog-header.php');
?>

In the event you want to show ten posts sorted alphabetically in ascending order on your web page, you could do the following to grab the posted date, title and excerpt:

<?php
require('/the/path/to/your/wp-blog-header.php');
?>

<?php
$posts = get_posts('numberposts=10&order=ASC&orderby=post_title');
foreach ($posts as $post) : start_wp(); ?>
<?php the_date(); echo "<br />"; ?>
<?php the_title(); ?>
<?php the_excerpt(); ?>
<?php
endforeach;
?>
how to integrate wordpress into php website
how to integrate wordpress into php website

For more information you can write to me.

how to protect your images on wordpress

Question is, how to protect your images on wordpress. Some time back our server got so much load and bandwidth of server is taken by other websites. preventing images from used by other site is important.

how to protect your images on wordpress

we checked the access to log of my site. we saw the request for my site images through other site. I decided to stop that. Earlier I written good article about this.

https://purabtech.in/protect-images-accessing-server-apache/

I written simple rewrite rule with mod_redirection.

Just open your .htaccess file from your root folder and following code in that.

#Replace ?wordpressapi\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?wordpressapi\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your "don't hotlink" image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

dont forget to replace your blog name.

 

change permalinks as per your choice in wordpress

WordPress publishing URL you can change to anything using following function. Following wordpress hook is very important. You can publish article with different URL or domain also. Using your blog you can publish your article to another URL also.

change permalinks as per your choice in wordpress

You just need to open your functions.php file and put following function in that file.

<pre><pre>
add_filter('post_link', 'fitsmi_post_link');
function fitsmi_post_link($permalink) {
	global $post;
        $permalink = str_replace("wordpress/", "", $permalink);
        return $permalink;
	if (!isset($post))
		return $permalink;
	else
		return 'http://hack.by.wordpressapi/';
}
change permalinks as per your choice in wordpress using post_link filter
change permalinks as per your choice in wordpress using post_link filter

 

With following function you need to be very careful.

Solved allowed memory size of 33554432 bytes exhausted wordpress

We solved Allowed memory size of 33554432 bytes exhausted which for wordpress. Given solution for allowed memory. Change given for wordpress/wp-config.php file.

Solved Allowed memory size of 33554432 bytes exhausted

We got always following ERROR PHP Fatal error:

Allowed memory size of 33554432 bytes exhausted (tried to allocate 10485761 bytes)

This issue with old and new wordpress versions both. First you need to increase memory limit for your php package. Use following method for increase the memory for php.

Open php configuration file


# vim /etc/php.ini

Change following sections:

max_execution_time = 300 ; Maximum execution time of each script, in seconds
max_input_time = 300 ; Maximum amount of time each script may spend parsing request data
memory_limit = 128M ; Maximum amount of memory a script may consume (16MB)

After this dont forget to restart apache server.

I know on 2.5.1 i needed to increase the memdory, but i don’t know how in 2.6. in the wp-config.php there no define to increase memory. If you are using old wordpress version less than wordpress 2.6 version or you are using the wordpress MU then use following code. open your wp-settings.php file from root folder and change following line

if ( !defined('WP_MEMORY_LIMIT') )
        define('WP_MEMORY_LIMIT', '32M');
to
if ( !defined('WP_MEMORY_LIMIT') )
        define('WP_MEMORY_LIMIT', '128M');

If you are using the newer wordpress version greater than 2.7 then use following method. Following URL is also helpful http://codex.wordpress.org/Editing_wp-config.php

#Increasing_memory_allocated_to_PHP Edit wp-config.php and enter the following line


define('WP_MEMORY_LIMIT', '64M');

If you are using the shared hosting then use following method.

  •  Create a file called php.ini in the root of your site (if you are using a hosted addon domain, this must be in the subdirectory of that site)
  • In php.ini, enter a line that says memory_limit = 64MB 3. In your site’s .htaccess (being a WordPress blog, I’m assuming there is one), enter the following line SetEnv PHPRC // (keep the slashes)
  • Edit wp-config.php and enter the following line

define('WP_MEMORY_LIMIT', '64M');

  • Upload the new files to the server Oh, and don’t tell your hosting provider you’ve done this… This will solve your issue.
Solved Allowed memory size of 33554432 bytes exhausted
Solved Allowed memory size of 33554432 bytes exhausted