First blog post via wp android app


Got wp android ap 🙂

Advertisements

How to change post thumbnail crop position in wordpress


I get many complaints about wordpress thumbnail (aka post featured image in wordpress 3) crop position lately. Many of my clients tell that they need top part of the image as thumbnail rather than the useless middle part. That’s why i dived into the core and got the solution for cropping top part of the thumbnails.

Here i will show you how to change crop behaviour of wordpress.
 

Cropping function is called image_resize and it is located in media.php.

Step1. Open media.php file under wp-includes folder.
Step2. Find the function named “image_resize_dimensions” (Around line 309). Unfortunately this function is not pluggable and doesn’t use any hooks so we will edit it directly. Find the lines:

$s_x = floor( ($orig_w - $crop_w) / 2 );$s_y = floor( ($orig_h - $crop_h) / 2 );

tep3. Those two variables define the start point of crop that will be used. Here is a sample image that will be cropped with those variables shown:

Step4. If you want top of part of the image as post featured image then $s_y value must remain zero. So we change that line to:

$s_y = 0; //floor( ($orig_h - $crop_h) / 2 );

Step5. Save the file and upload it to wp-includes folder.

Last Step. A post image is cropped at the first time it is uploaded. To update thumbnails you need this great plugin calledRegenerate Thumbnails. This plugin takes post thumbnails and crops them again using your latest media settings. After you install it click on the “Regenerate All Thumbnails” button under tools. It will automatically crop all the post thumbnails again. This will take a minute or two depending on your server and number of posts you have. After the regeneration is complete all your thumbnails will be cropped from top.

WordPress black and white thumbnail


First we need to create a new thumbnail using add_image_size(). We’ll use the same thumbnail settings from the WordPress Media page in the wp-admin. Add this to your functions.php file within the PHP tags:

add_action(‘after_setup_theme’,’bw_images_size’);function bw_images_size() {    $crop = get_option(‘thumbnail_crop’)==1 ? true : false;    add_image_size(‘thumbnail-bw’, get_option(‘thumbnail_size_w’), get_option(‘thumbnail_size_h’), $crop);}

With that in place, we can now add the following function which will automatically create a black and white thumbnail:

add_filter(‘wp_generate_attachment_metadata’,’bw_images_filter’);

function bw_images_filter($meta) {

    $file = wp_upload_dir();

    $file = trailingslashit($file[‘path’]).$meta[‘sizes’][‘thumbnail-bw’][‘file’];

    list($orig_w, $orig_h, $orig_type) = @getimagesize($file);

    $image = wp_load_image($file);

    imagefilter($image, IMG_FILTER_GRAYSCALE);

    //imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR);

    switch ($orig_type) {

        case IMAGETYPE_GIF:

            $file = str_replace(“.gif”, “-bw.gif”, $file);

            imagegif( $image, $file );

            break;

        case IMAGETYPE_PNG:

            $file = str_replace(“.png”, “-bw.png”, $file);

            imagepng( $image, $file );

            break;

        case IMAGETYPE_JPEG:

            $file = str_replace(“.jpg”, “-bw.jpg”, $file);

            imagejpeg( $image, $file );

            break;

    }

    return $meta;

}

Whenever you upload an image, this function will create a new black and white thumbnail automatically. I also added a Gaussian Blur but commented it out. Remove those two slashes “//” to add a Gaussian Blur to your new black and white thumbnail. See otheravailable filters.

get_post_thumbnail();1 within your WordPress loop to display the two images for the effect:

Once you’ve added the above code, you can use.

get_post_thumbnail();1 within your WordPress loop to display the two images for the effect:

1if(function_exists(‘has_post_thumbnail’) && has_post_thumbnail()) {

    echo ‘<a href=”’.get_permalink().’” class=”fade-image”>’;

    the_post_thumbnail(‘thumbnail-bw’, array(‘class’=>’fade-image-a’));

    the_post_thumbnail(‘thumbnail’, array(‘class’=>’fade-image-b’));

    echo ‘</a>’;

}

WordPress sitemap HTML using template


Create a template and Paste this

<h2 id="authors">Authors</h2>
<ul>
<?php
wp_list_authors(
  array(
    'exclude_admin' => false,
  )
);
?>
</ul>

<h2 id="pages">Pages</h2>
<ul>
<?php
// Add pages you'd like to exclude in the exclude here
wp_list_pages(
  array(
    'exclude' => '',
    'title_li' => '',
  )
);
?>
</ul>

<h2 id="posts">Posts</h2>
<ul>
<?php
// Add categories you'd like to exclude in the exclude here
$cats = get_categories('exclude=');
foreach ($cats as $cat) {
  echo "<li><h3>".$cat->cat_name."</h3>";
  echo "<ul>";
  query_posts('posts_per_page=-1&cat='.$cat->cat_ID);
  while(have_posts()) {
    the_post();
    $category = get_the_category();
    // Only display a post link once, even if it's in multiple categories
    if ($category[0]->cat_ID == $cat->cat_ID) {
      echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
    }
  }
  echo "</ul>";
  echo "</li>";
}
?>
</ul>


WP plugin from scratch


Recently I started a project in WordPress in which I needed to create few plugins. I had no idea where to start from. But searching the web for few minutes gave me plenty of information to boost me up. So here I will show you how to create a wordpress plugin from scratch.

First of all you must decide a unique name for your plugin beacause WordPress’s plugin directory contains a number of plugins and your name may conflict with that of others. So find a unique name:)

Lets name our plugin ‘AwesomeWP’. 
Here is the directory structure for our plugin: rootwp-contentpluginsAwesomeWPstart.php
Note that we have created a new directory ‘AwesomeWP’ for our plugin. Although you can place your plugin file directly under wp-contentplugins directory, but making a separate directory helps you managing your files in an elegant way.
Now open wp-contentpluginsAwesomeWPstart.php and write following lines in the file:

?

1234567891011<?php/*Plugin Name: AwesomeWPPlugin URI: http://webspeaks.in/Description: My first Awesome wordpress pluginVersion: 1.0Author: Arvind BhardwajAuthor URI: http://webspeaks.in/License: GPL*/?>


Go to wordpress admin > plugins and you will see the AwesomeWP listed there. Happy to see it? Hmmmm! Its the comment part in the header portion of file that helps WordPress finding you plugin.
Now lets add some functionality to our plugin as till now it does nothing. Add following lines to our start.php
?

12345add_action('init','awesome');function awesome(){ echo "WordPress is just Awesome!!";}

The ‘init’ is called when WordPress initializes. So we have called a function ‘awesome’ on initialization of our blog. Note that no braces are required during this function call. After activating the plugin you will see ‘WordPress is just Awesome!!’ printed on top of your page, means it works!

Modifying the Post:
WordPress provides us very powerful means to modify literally any part of the wordpress blog. Like we can change the outcome of the posts as to our desire by just adding following lines of code in our plugin file:
?

12345678add_filter('the_content', 'modifyPost'); function modifyPost($content){$signature = 'Have fun with plugins!';return $content.$signature;}

What actually happened here is that we applied a WordPress filter ‘the_content’ in our plugin. This hook is called when post is diplayed on frontend. So at the time of displaying post, we added our custom text below the post. Note that the content of our post is automatically made available in the callback function ‘modifyPost’ through the wordpress filter. This is the beauty of WordPress.
So we have learnt how to write our first WordPress plugin adn modify our posts through plugin. Happy coding:)

Complete Plugin File:
?

12345678910111213141516171819202122232425262728<?php/*Plugin Name: AwesomeWPPlugin URI: http://webspeaks.in/Description: My first Awesome wordpress pluginVersion: 1.0Author: Arvind BhardwajAuthor URI: http://webspeaks.in/License: GPL*/?><?phpadd_action('init','awesome');/*Called when WordPress Initializes*/function awesome(){ echo "WordPress is just Awesome!!";} add_filter('the_content', 'modifyPost');  /*This tells WordPress that every time it's going to display the content of a post or page, it            should run it through our modifyPost() function.*/function modifyPost($content){$signature = 'Have fun with plugins!';return $content.$signature;} ?>

WordPress Adding Navigation Menus


NOTE : TO DISPLAY MENU : 

<?php wp_nav_menu( array( ‘container_class’ => ‘menu-header’, ‘theme_location’ => ‘top-menu’ ) ); ?>

Adding A Navigation Menu To Your Template

If your theme was designed before the release of WordPress 3, it probably won’t have the new menu system built in unless the theme designer has updated it since it was released. Thankfully, adding the menu to your template is very straight forward. To call the navigation menu all you have to do is use the command below (we will talk about the parameters you can pass to the function shortly):

 <?php wp_nav_menu($args); ?>

You simply need to add the above code to the area you want your menu to be displayed (e.g. header, footer etc). If you are only planning on adding one menu, that’s the only call to the function you need to make in your template. If you are planning on adding two or more menus, you need to add some code to your functions.php template. Through testing I verified that wp_nav_menu() will simply call the first menu added unless specified i.e. if you don’t add the appropriate code to the functions.php template the same menu will be linked in the header and footer even if you have created separate menus for each area.

// Registering Menus For Theme
 
add_action( 'init', 'register_my_menus' );
 
function register_my_menus() {
	register_nav_menus(
		array(
			'primary-menu' => __( 'Primary Menu' ),
			'secondary-menu' => __( 'Secondary Menu' ),
			'tertiary-menu' => __( 'Tertiary Menu' )
		)
	);
}

In total wp_nav_menu has 15 parameters to choose from. To specify what menu you are calling, you need to use the $theme_location parameter, referencing the name you registered in your functions.php template.

For example, using the example I used above; after I have registered my three menu areas in functions.php, I would add the following code to my header.php template to display my main navigation menu:

<?php wp_nav_menu (array ( 'theme_location' => 'main-nav-menu') ); ?>

I would then add this code to my sidebar.php template to add the sidebar menu to my theme:

<?php wp_nav_menu (array ( 'theme_location' => 'sidebar-menu') ); ?>

Finally, I would add the code below to my footer.php template to add the footer menu to my theme:

<?php wp_nav_menu (array ( 'theme_location' => 'footer-menu') ); ?>

Of course, the examples above only have one parameter. Depending on how we have styled our menus, we may pass several to the function. Here is a list of the 15 parameters you can use with wp_nav_menu().

  • $theme_location – The menu you want to display (as registered in your functions.php template).
  • $menu – Call a menu using id, name or slug.
  • $container – Whether to wrap the ul tag with a div or nav.
  • $container_class – The class that is applied to the container.
  • $container_id – The id that is applied to the container.
  • $menu_class – The class to be applied to the ul element of the menu.
  • $menu_id – The id to be applied to the ul element of the menu.
  • $echo – Whether to echo the menu or return it.
  • $fallback_cb – If no menu exists, which fallback function to use.
  • $before – Text before the anchor link.
  • $after – Text after the anchor link.
  • $link_before – Text before the link text.
  • $link_after – Text after the link text.
  • $depth – How many levels of the menu hierarchy to be displayed.
  • $walker – Custom walker object.

Styling Your Menu

You should by now have a basic understanding of how to add a menu to your theme. As always, I recommend trying this process in your WordPress Test Area before adding it to a live website. It is relatively easy to add the new menu system to your theme however it will probably take you a little while to get your menu styled exactly the way you want it (unless you’re a CSS whizz!).

I was lucky that I didn’t have to style my menu from scratch, I just had to make sure I changed the previous code in my header template to link to my classes correctly using the wp_nav_menu function. As you can see from the image below, at the time of upgrading my menu my navigation menu had a number of unique features such as a dark background image, a unique image for the home page link and a search box.

One of the first things I had to address was ensuring the navigation background container was linked properly. WP Mods author Pippin Williamson advised that he usually puts a wrapper around the menu and then styles the ul and li elements accordingly. This is how I assume most CSS coders do it. As we saw previously, we could also specify the container with a parameter.

For example, if we wanted to wrap our menu using the class menu-wrapper, we could do it like this:

<div class="menu-wrapper">
<?php wp_nav_menu( ); ?>
</div>

This could also be achieved by using the following:

<?php wp_nav_menu (array ( 'container' => 'div', 'container_class' => 'menu-wrapper' ) ); ?>

In the end, I had to use wrap my menu inside a division rather than specifying the container through the wp_nav_menu function, as I wanted to include a search box at the right hand side of the menu.

As I noted above, the home page link on WP Mods uses an image. Thankfully, styling an individual link in a WordPress menu is very easy. Clicking on the ‘Screen Options’ link at the top of the Menu page will bring down a drop down menu. From there you will find an option to display ‘CSS Classes’ under the heading ‘Show advanced menu properties’.

Screen Options CSS Classes

Once you have clicked on ‘CSS Classes’ you will have the option to see a new option in your links which lets you customise each link individually. This allowed me to style my home page link differently by creating a class called ‘home-page’. By using this method you can customise each link in your menus differently. This can be useful, particularly for those who want to use images as links in their menu or add images beside their links.

Custom Navigation Style

There are also several default classes which allow you to change the link of a page which is currently being viewed. WP Beginner have a fantastic walkthrough entitled How to Style WordPress Navigation Menus which details these classes. Classes include current_page_item, which let you style the current page; and menu-item-home, which lets you customise the home link (though I preferred linking via the menu widget).

Classes List:

  • current_page_item – Style the current page.
  • current-cat – Style the current category.
  • menu-item – Style any other menu item.
  • menu-item-type-taxonomy – Style category links.
  • menu-item-type-post_type – Style page links.
  • menu-item-type-custom – Style custom items.
  • menu-item-home – Style the home page link.

Summary

I’m a huge fan of the way WordPress allows you to easily add Navigation Menus. If your current theme does not have this feature integrated then it may be worth upgrading your design with the code discussed in this article so that you can modify links in future easily.

I don’t profess to be an expert on WordPress menus however if you are unsure about any aspect of this tutorial please leave a comment and I’ll do my best to help.

Good luck,
Kevin

Useful Links