WordPress function: Get category ID using category name

When coding a WordPress site, you often need to get a category ID. If you ever wanted to be able to get a category ID from the category name, then just read this recipe, I’m pretty sure you will like it.
As usual, let’s start by pasting the function in your functions.php file:
function get_category_id($cat_name){
$term = get_term_by('name', $cat_name, 'category');
return $term->term_id;
}

Once you saved the file, just call the function with your category name as a parameter. Example:

$category_ID = get_category_id('Category Slug');

Posted in WP Code | Leave a comment

Hide posts in the “uncategorized” category

These are two snippets that accomplish mostly the same thing.

The first snippet hides the display of content if it’s post is assigned to the Uncategorized category.

The second snippet hides the display of content if it’s post is assigned to the default WP category, even if it has been renamed.

These are useful in different cases. In the first, if a user eventually renamed “Uncategorized” to something more useful, then it would be displayed.

<?php
	// Hide the display of something if it has the category named "Uncategorized"
	if( !in_category( 'Uncategorized' ) ) {
        	// do something like:
        	the_category( ', ' );
        }

	// Hide the display of something if it uses the default category, initially named "Uncategorized"
	if( !in_category( 1 ) ) {
        	// do something like:
        	the_category( ', ' );
        }

?>
Posted in WP Code | Leave a comment

Redirect user after login

This snippet will help you to redirect login user based on their role.
Open function.php file in your theme and add this function.

<?php

function redirect_user_on_role()
{
//retrieve current user info
global $current_user;
get_currentuserinfo();
//If login user role is Subscriber
else if ($current_user-&gt;user_level == 0)
{
wp_redirect( home_url() ); exit;
}
//If login user role is Contributor
else if ($current_user-&gt;user_level &gt; 1)
{
wp_redirect( home_url() ); exit;
}
//If login user role is Editor
else if ($current_user-&gt;user_level &gt;8)
{
wp_redirect( home_url() ); exit;
}
// For other rolse
else
{
$redirect_to = 'http://google.com/';
return $redirect_to;
}
}
add_action('admin_init','redirect_user_on_role');

?>
Posted in WP Code | Leave a comment

How to Create a Simple WordPress Tag Cloud using wp_tag_cloud

Here’s the exact HTML and PHP code I use to display tags for this website:

div class="stagswrap">
<h3>Popular Tags</h3>
<?php wp_tag_cloud('smallest=15&largest=15&number=20&orderby=count&
order=DESC&exclude=312&unit=px'); ?>
</div>

This code produces this (as seen on my right sidebar):
tag1
Here are the CSS codes I used:

.stagswrap a {
background: #FFC414;
color: #FFF;
display: inline-block;
margin: 0 4px 8px 0;
padding: 2px 10px;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px;
font-size: 15px;
}
Posted in Designer Tips, Developer Tips | Leave a comment

How to Increase the Autosave Interval

autosave
Here’s a short line of code you can add to your wp-config.php file to increase the post autosave interval in WordPress.

Open the wp-config.php file (in the root folder) and add this line of code at the bottom:

/* increase autosave interval */
define('AUTOSAVE_INTERVAL', 600); // 10 minutes (60 seconds x 10)
Posted in Developer Tips, WP Code | 2 Comments

Hiding Back To Top

When scroll down the back to top will show. When scroll back to top it will become hide. Place the script before the body close.

<!-- Jquery Script-->
<script type="text/javascript">
			jQuery(document).ready(function(){
				jQuery(function () {
				var scrollDiv = document.createElement("div");
				jQuery(scrollDiv).attr("id", "toTop").html("^ Back to Top").appendTo("body");
				jQuery(window).scroll(function () {
						if (jQuery(this).scrollTop() != 0) {
							jQuery("#toTop").fadeIn();
						} else {
							jQuery("#toTop").fadeOut();
						}
					});
					jQuery("#toTop").click(function () {
						jQuery("body,html").animate({
							scrollTop: 0
						},
						800);
					});
				});
			});
</script>
<!-- CSS For the text-->
#toTop {width:100px;z-index: 10;border: 1px solid #333; background:#121212; text-align:center; padding:5px; position:fixed; bottom:0px; right:0px; cursor:pointer; display:none; color:#fff;text-transform: lowercase; font-size: 0.9em;}
Posted in Developer Tips | Leave a comment

Page Font Size Change Option

<!--Font increase start-->
<script type='text/javascript'>
		jQuery(function(){
		jQuery('.font_increase_tool img').click(function(){
			var ourText = jQuery('p,.Contact_Detail_heading,.Contact_Details,.Contact_email,.rental_facilities_sub_title,.rental_facilities_contents,..rental_facilities_contentmain_entry ul li a,.key_word,.key_word1,.key_word2,.h3,strong,.artist_in_action_contentmain_entry,.artist_bottom,td,th,.artist_in_action_contentmain_entry div strong,.key_word2 h3 strong,.rental_facilities_contentmain_entry div');
			var currFontSize = ourText.css('fontSize');
			var finalNum = parseFloat(currFontSize, 10);
			var stringEnding = currFontSize.slice(-2);
			if(this.id == 'large') {
				finalNum *= 1.2;
			}
			else if (this.id == 'small'){
				finalNum /=1.2;
			}
			ourText.css('fontSize', finalNum + stringEnding);
		});
	});

	</script>
<!--Font increase end-->
<!--HTML Code-->
<div class="font_size">
            	<div class="font_increase_tool">
                		<div class="font_text">font size</div>

                        <div class="font_minus">

                        	<img src="image_location/font_decrease.gif" alt="font_decrease" id="small" />
                        </div>
                        <div class="font_plus">

                        	<img src="image_location/font_increase.gif" alt="font_increase" id="large" />
                        </div>
                </div>
Posted in Developer Tips | Leave a comment

Retrieve attached images of a post

<?php
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => null );
$attachments = get_posts( $args );
if ($attachments) {
	foreach ( $attachments as $post ) {
		setup_postdata($post);
		the_attachment_link($post->ID, false);
	}
}
?>
Posted in WP Code | Leave a comment

How to increase WordPress memory limit, the easy way

If you ever had error that reads “Allowed memory size of xxx bytes exhausted”, then you need to increase WordPress memory limit. This can be done very easily and may solve really frustrating problems.
Simply open your wp-config file, located at the root of your WordPress install, and paste the following code in it. Once saved, WordPress will be able to use as much memory as specified.

define('WP_MEMORY_LIMIT', '96M');
Posted in WP Code | Leave a comment

Change WordPress “from” email header

By default, the default WordPress email adress looks like WordPress@yoursitename.com. Want to use your real email and username instead? Just read this recipe.
This recipe is pretty easy to implement: Just paste the following code into your functions.php theme:

function res_fromemail($email) {
    $wpfrom = get_option('admin_email');
    return $wpfrom;
}

function res_fromname($email){
    $wpfrom = get_option('blogname');
    return $wpfrom;
}

add_filter('wp_mail_from', 'res_fromemail');
add_filter('wp_mail_from_name', 'res_fromname');
Posted in Developer Tips | Leave a comment

WordPress shortcode: Display a thumbnail of any website

The first step is to create the shortcode. To do so, simply paste the code below into your functions.php file.

function wpr_snap($atts, $content = null) {
        extract(shortcode_atts(array(
			"snap" => 'http://s.wordpress.com/mshots/v1/',
			"url" => 'http://www.catswhocode.com',
			"alt" => 'My image',
			"w" => '400', // width
			"h" => '300' // height
        ), $atts));

	$img = '<img src="' . $snap . '' . urlencode($url) . '?w=' . $w . '&h=' . $h . '" alt="' . $alt . '"/>';
        return $img;
}

add_shortcode("snap", "wpr_snap");

Once done, you can use the snap shortcode, as shown in the following example:

[snap url="http://www.catswhocode.com" alt="My description" w="400" h="300"]

This will display a snapshot of CatsWhoCode. Please note that the height parameter can be ommitted.

Thanks to Valentin Brandt for the cool tip!

Posted in Developer Tips | Leave a comment

How to display a thumbnail from a Youtube using a shortcode

First, you need to create the shortcode. To do so, copy the code below and paste it into your functions.php file.

/*
    Shortcode to display youtube thumbnail on your wordpress blog.
    Usage:
    [youtube_thumb id="VIDEO_ID" img="0" align="left"]
    VIDEO_ID= Youtube video id
    img=0,1,2 or 3
    align= left,right,center
*/
function wp_youtube_video_thumbnail($atts) {
     extract(shortcode_atts(array(
          'id' => '',
          'img' => '0',
          'align'=>'left'
     ), $atts));
    $align_class='align'.$align;
    return '<img src="<a href="http://img.youtube.com/vi/'.$id.'/'.$img.'.jpg&quot" rel="nofollow">http://img.youtube.com/vi/'.$id.'/'.$img.'.jpg&quot</a>; alt="" class="'.$align_class.'" />';
}
add_shortcode('youtube_thumb', 'wp_youtube_video_thumbnail');

Once done, you can use the shortcode. It accept 3 parameters: The video ID, the image size (0 for 480*360px, 1 for 120*90) and the image alignment.


[youtube_thumb id="rNWeBVBqo2c" img="0" align="center"]
Posted in Developer Tips, WP Code | Leave a comment

WordPress Nav Menu

Activate menu in function.php
----------------------------------

< ?php
// This theme uses wp_nav_menu() in one location.
register_nav_menus( array('my_nav' => __( 'Primary Navigation', 'sw theme' ),
'secondary' => __('Secondary Navigation', 'sw theme')
));
?>

 <a href="http://vipin.x10.mx/160/#more-160" class="more-link">(more...)</a>
Posted in Developer Tips | Comments Off

Admin Translate Plugin


Writing multilingual content is already hard enough, why make using a plugin even more complicated? WordPress have an easy to use interface for managing a fully multilingual web site with qtranslate.

http://wordpress.org/extend/plugins/qtranslate/

Posted in WP Code | 1 Comment

Prohibit access to the file. “Htaccess” in your WordPress installation!

#Protection 403 du fichier htaccess
<files .htaccess>
 Order Allow,Deny
 Deny from all
</files>
Posted in Developer Tips | Comments Off

Simple Pay Pal Button

function cwc_donate_shortcode( $atts ) {
    extract(shortcode_atts(array(
        'text' => 'Make a donation',
        'account' => 'youremail@id.here',
        'for' => 'Testng My Page',
    ), $atts));

    global $post;

    if (!$for) $for = str_replace(" ","+",$post->post_title);

    return '<a class="donateLink" href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation+for+'.$for.'">'.$text.'</a>';

}
add_shortcode('donate', 'cwc_donate_shortcode');

//Shoert Code-> [donate]
Posted in Developer Tips | Comments Off

Change The Uploading Size

Use this code in .htaccess, It will increase the limit to 25MB

php_value upload_max_filesize 25M
php_value post_max_size 25M
php_value max_execution_time 250
php_value max_input_time 250

# BEGIN WordPress
Posted in WP Code | Comments Off

Excerpt Length & Text

Use These codes in function.php

//Set the Read more in excerpt
function excerpt_ellipse($text) {
return str_replace('[...]', ' <a href="'.get_permalink().'">[Read more]</a>', $text); }
add_filter('the_excerpt', 'excerpt_ellipse');
//Set excerpt as [...]
function trim_excerpt($text) {
return rtrim($text,'[...]');}
add_filter('get_the_excerpt', 'trim_excerpt');
//Length Adjust
function new_excerpt_length($length) {
return 20;}
add_filter('excerpt_length', 'new_excerpt_length');
Posted in WP Code | Comments Off

Include Left Sidebar

<!-- start left sidebar -->
<?php include("leftsidebar.php"); ?>
<!-- end leftsidebar  -->
Posted in WP Code | Comments Off

Permalink With Substring

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php echo substr(the_title('', '', FALSE), 0, 30);?>
</a>
Posted in WP Code | Comments Off

Query Post

//Simple Query
<?php query_posts('showposts=4&cat='); ?>
<?php wp_reset_query();?>

//Query with Specific Page
<?php if(is_page(9)): query_posts('showposts=4'); ?>
<?php endif; wp_reset_query();?>
Posted in WP Code | Comments Off

Link & Image Location

<a href="<?php bloginfo( 'url' );echo '/?page_id=9/'; ?> ">
<img class="image_class" src="<?php bloginfo('template_directory');?>/images/image.jpg" alt=""/>
</a>
Posted in WP Code | Comments Off

Page Template

<?php /*template name:Template Name*/ ?>
Posted in WP Code | Comments Off

Jquery Include

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
Posted in WP Code | Comments Off

Set HTML Default Text Editor

The WYSIWYG editor which comes default on install of WordPress can be annoying for those who enjoy working in HTML. I find that HTML is easily the best way to edit articles. With this short bit of code inside your functions.php it’s a simple matter to shift between default states.

// Set HTML as Default
add_filter( 'wp_default_editor', create_function('', 'return "html";') );
Posted in Developer Tips | Comments Off

Google Analytics without Theme Edits

I’m sure as webmasters we are all familiar with using Google Analytics. It’s a short amount of JavaScript to implement and start tracking visitor information. This function inside your theme’s functions.php will automatically place your code on every single page dynamically. You just need to add your JS code inside the function by replacing the filler comment text.

<?php add_action('wp_footer', 'ga_custom');
function ga_custom() { ?>
// add google analytics code here!
<?php } ?>
Posted in Developer Tips | Comments Off

Implement Search Box in Nav Menu

It can be difficult editing your template to find room for a search box. WordPress isn’t always the most stable system when it comes to search queries – but with this code below things become much more manageable. Add this function into your functions.php file inside your template folder.

add_filter('wp_nav_menu_items','add_search_box', 10, 2);
function add_search_box($items, $args) {
ob_start();
get_search_form();
$searchform = ob_get_contents();
ob_end_clean();
$items .= '<li>' . $searchform . '</li>';
return $items;
}
Posted in Developer Tips | Comments Off

Implement Maintenence Mode

Whenever you’re working on your blog and wish to blockade traffic from the main website, maintenence mode is your best option. Add the below function and action into your function.php file within your template folder.

function maintenace_mode() {
if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {
die('Maintenance.');
}
}
add_action('get_header', 'maintenace_mode');
Posted in Developer Tips, WP Code | Comments Off

Properly Include jQuery

jQuery is the best extensible JavaScript library to date. WordPress allows a simple way of including the latest version through an internal function.

<?php wp_enqueue_script("jquery"); ?>
Posted in WP Code | Comments Off