Wednesday, July 31, 2013

WordPress function to check if the current post is a custom post type

WordPress function to check if the current post is a custom post type


Just paste this code into your functions.php file:


function is_custom_post_type() {
    global $wp_query;
       
    $post_types = get_post_types(array('public'   => true,'_builtin' => false),'names','and');
   
    foreach ($post_types  as $post_type ) {
        if (get_post_type($post_type->ID) == get_post_type($wp_query->post->ID)) {
            return true;
        } else {
            return false;
        }
    }
}

Once complete, we can use the function as display below.

P.S. : function can be used outside the loop:

if (is_custom_post_type()) {
    //Current post is a custom post type
}

Saturday, June 1, 2013

How to automatically insert a list of related articles below the post

In wordpress When a reader finished reading one of your blog posts, you can suggesting him to read other article that he might like as well? Here is a quick solution to automatically display related posts (based on category) below the current post

First, you have to  paste the code below into the functions.php file from your theme.

// "More from This Category" list by Barış Ünver @ Wptuts+
function wptuts_more_from_cat( $title = "More From This Category:" ) {
    global $post;
    // We should get the first category of the post
    $categories = get_the_category( $post->ID );
    $first_cat = $categories[0]->cat_ID;
    // Let's start the $output by displaying the title and opening the <ul>
    $output = '<div id="more-from-cat"><h3>' . $title . '</h3>';
    // The arguments of the post list!
    $args = array(
        // It should be in the first category of our post:
        'category__in' => array( $first_cat ),
        // Our post should NOT be in the list:
        'post__not_in' => array( $post->ID ),
        // ...And it should fetch 5 posts - you can change this number if you like:
        'posts_per_page' => 5
    );
    // The get_posts() function
    $posts = get_posts( $args );
    if( $posts ) {
        $output .= '<ul>';
        // Let's start the loop!
        foreach( $posts as $post ) {
            setup_postdata( $post );
            $post_title = get_the_title();
            $permalink = get_permalink();
            $output .= '<li><a href="' . $permalink . '" title="' . esc_attr( $post_title ) . '">' . $post_title . '</a></li>';
        }
        $output .= '</ul>';
    } else {
        // If there are no posts, we should return something, too!
        $output .= '<p>Sorry, this category has just one post and you just read it!</p>';
    }
    // Let's close the <div> and return the $output:
    $output .= '</div>';
    return $output;
}
 
 
 
Now open your single.php file in theme folder and call the function as describe below, where you'd like to display the related posts:

<?php echo wptuts_more_from_cat( 'More From This Category:' ); ?>
 

Friday, April 26, 2013

Exclude certain categories from being displayed in Wordpress

Exclude certain categories from being displayed in Wordpress

Thre are two ways to hide posts from certain categories to be displayed on the wordpress blog. You can either put this code inside the loop

    <?php  
    if ( have_posts() ) : query_posts($query_string .'&cat=-1,-2'); while ( have_posts() ) : the_post(); 
    ?> 
         

or you van use the plugin "Advanced Category Excluder" from wordpress plugin directory.


Add SVG upload support to WordPress blog

How to add SVG upload support to your WordPress blog

The WordPress uploader generally do not support the SVG format by default. But this file format is becoming quite popular nowadays, Thee simple example can guide you to add SVG upload to your WordPress install.

You have to simply just add the code below to your functions.php file. After that SVG upload will be supported autometically once the file is saved.

add_filter('upload_mimes', 'my_upload_mimes');

function my_upload_mimes($mimes = array()) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}


Wednesday, April 10, 2013

Redirect to post if search results only returns one post

In Wordpress when a visitor search your website using WordPress built-in search engine function, the search results are displayed as a list. The following functionality can improve the search engine by automatically redirecting the visitor to the post if there is only one post is found by WordPress search engine.


You need to just paste the following code into the functions.php file:

add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
        }
    }
}

Friday, April 5, 2013

How to add hook in PrestaShop 1.5

How to add hook in PrestaShop 1.5

Sometimes we need to add custom hook in prestashop
The process of Hook adding in FrontController.php in PrestaShop 1.5 is different from the other previous version of prestashop like PreataShop 1.4 but for database and installing module parts are still the same way as it before.

1. Open “FrontController.php” from /override/classes/controller/
Default file is looks like this

<?php
 
class FrontController extends FrontControllerCore
{
 
}
 
2. Then, add this following code from main FrontController.php
 
<?php
 
class FrontController extends FrontControllerCore
{
    public function initContent()
    {
        $this->process();
        if (!isset($this->context->cart))
                $this->context->cart = new Cart();
        if ($this->context->getMobileDevice() == false) {
            // These hooks aren't used for the mobile theme.
            // Needed hooks are called in the tpl files.
            if (!isset($this->context->cart))
                $this->context->cart = new Cart();
            $this->context->smarty->assign(array(
                /* === START: DO NOT TOUCH IT */
                'HOOK_HEADER' => Hook::exec('displayHeader'),
                'HOOK_TOP' => Hook::exec('displayTop'),
                'HOOK_LEFT_COLUMN' => ($this->display_column_left ? Hook::exec('displayLeftColumn') : ''),
                'HOOK_RIGHT_COLUMN' => ($this->display_column_right ? Hook::exec('displayRightColumn', array('cart' => $this->context->cart)) : ''),
                /* === END: DO NOT TOUCH IT */
                 
                /* === START: ADD HOOK | EXAMPLE */
                'HOOK_MY_USER' => Module::hookExec('myUser'),
                'HOOK_MY_CATEGORIES' => Module::hookExec('myCategories'),
                'HOOK_SEARCH' => Module::hookExec('mySearch')
                /* === END: ADD HOOK | EXAMPLE */
            ));
        } else {
            $this->context->smarty->assign(array(
                'HOOK_MOBILE_HEADER' => Hook::exec('displayMobileHeader'),
            ));
        }
    }
}
 
Now save he file and its done.. 



 

How to change mail color in PrestaShop 1.5

How to change mail color in PrestaShop 1.5


Just follow the simple steps
Go to
1. Preferences -> Themes






Thenge change in the manner of the following way

Now
2. Save and Done!


Tuesday, April 2, 2013

How to activate link manager on WordPress 3.5 (and newer)

How to activate link manager on WordPress 3.5 (and newer)

The new WordPress version like 3.5 (and newer) , wordpress have left out the Link Manager facility from the admin area. In the following way we can bring it back!


You can just paste this code into your functions.php file and it will works

<?php

    //Activate the Link Manager built in to the WordPress admin
    add_filter( 'pre_option_link_manager_enabled', '__return_true' );

?>

How to directly include Typekit fonts on your WordPress theme

How to directly include Typekit fonts on your WordPress theme

How to directly include Typekit fonts on your WordPress theme

Typekit is a very useful service which allow us to use countless different fonts on our website or blog. Typekit provide a WordPress plugin by using this we can easily add their fonts to our WordPress site, but there are no built-in solution by which we can integrating Typekit fonts directly to your theme. Please following tricks can do so.

Edit the code below and update the .js file path on line 2. Then, simple paste it on your functions.php file. Save the file, and you're done!

function theme_typekit() {
    wp_enqueue_script( 'theme_typekit', '//use.typekit.net/xxxxxxx.js');
}
add_action( 'wp_enqueue_scripts', 'theme_typekit' );

function light_typekit_inline() {
  if ( wp_script_is( 'theme_typekit', 'done' ) ) { ?>
      <script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<?php }
}
add_action( 'wp_head', 'theme_typekit_inline' );


Monday, March 25, 2013

How To Add HTML Links To Standard Prestashop E-Mail Messages

How To Add HTML Links To Standard Prestashop E-Mail Messages


Standard Prestashop order messages section settings do not allow us creating messages which would contain HTML links with clickable anchor texts. But if you want that feature there is still a workaround which you can use to add HTML links to your e-mail messages.

To do this it is necessary to override the method AdminOrderController.php PostProcess as follows:
$customer_message->message = htmlentities(Tools::getValue('message'), ENT_COMPAT, 'UTF-8');


Change to
$customer_message->message = Tools::getValue('message');

How To Put Prestashop Category List In Alphabetical Order

How To Put Prestashop Category List In Alphabetical Order

In prestashop when new categories are added to the multi-level navigation blocks, they are placed at the end position of the list which makes it look quite messy. So to sort all the categories in alphabetical order we need to do the following:

In the file modules/blocklayered/blocklayered.php change this line:
GROUP BY c.id_category ORDER BY c.nleft, c.position';

To this one:
GROUP BY c.id_category ORDER BY cl.name ASC, c.nleft, c.position';


Thursday, March 21, 2013

Dynamic Copyright Date in WordPress Footer

Dynamic Copyright Date in WordPress Footer

Sometimes you will will see various websites with outdated copyright dates. Some of the websites show the current year as their copyright date. This is not a very good sign for a website.To give your users a little background information about your website, you should display the copyright date like: © 2010 – 2012. You can do this by just pasting the following code:


function updated_copyright() {
global $wpdb;
$copyright_dates = $wpdb->get_results("
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb->posts
WHERE
post_status = 'publish'
");
$output = '';
if($copyright_dates) {
$copyright = "&copy; " . $copyright_dates[0]->firstdate;
if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
$copyright .= '-' . $copyright_dates[0]->lastdate;
}
$output = $copyright;
}
return $output;
}




Once you haveadd this function, now open your footer.php file in theme folder  add the following code in the footer or wherever you want to display the dynamic copyright date:
  <?php echo updated_copyright(); ?>

This function looks for the date of your first post, and the date of your last post. It then echos the years wherever you call the function.


Change the Footer in WordPress Admin Panel

Change the Footer in WordPress Admin Panel

In the following way ,you can change the footer of your wordPress themes by adding the following guideline. You need to just paste the following code:

function remove_footer_admin () {
echo 'Powered by <a href="http://www.sandipdas.in" target="_blank">Sandip Das</a> | Designed by <a href="http://php-mysql-guide.blogspot.com/" target="_blank">PHP MYSQL GUIDE</a></p>';
}

add_filter('admin_footer_text', 'remove_footer_admin');




Wednesday, March 20, 2013

How to redirect users to a random post

How to redirect users to a random post


To do this follow the instruction below
Create a new file and name it page-random.php and just paste the code below in it:

// set arguments for get_posts()
$args = array(
    'numberposts' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = get_posts ( $args );

// process the database request through a foreach loop
foreach ( $my_random_post as $post ) {
  // redirect the user to the random post
  wp_redirect ( get_permalink ( $post->ID ) );
  exit;
}

Now, upload the page-random.php file to your wordpress theme directory. After upload login to your WP dashboard and create a new page, called "random" [If you dont call it random, otherwise, the standard page layout will apply, you can check Wordpress Codex for more details about page hierarchy].

Now after you published the random page, if any user  visit the http://www.website.com/random page, he will be automatically redirected to a random post.


How to only display the author posts in the admin post list

How to only display the author posts in the admin post list

In a multi-author blog, the code is very useful to allow each author to only see his own posts in the wordpress admin post list. The following is a simple code snippet to do it.

So you have to paste the code below into the theme functions.php file. Now saved the file, and then authors will only see only their own posts in the admin post list.

<?php

function mypo_parse_query_adminonly( $wp_query ) {
    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/edit.php' ) !== false ) {
        if ( !current_user_can( 'level_10' ) ) {
            global $current_user;
            $wp_query->set( 'author', $current_user->id );
        }
    }
}

add_filter('parse_query', 'mypo_parse_query_adminonly' );

?>


Thursday, March 14, 2013

How to run the loop outside of WordPress

How to run the loop outside of WordPress

If you need to access your WordPress content and need to run a loop OUTSIDE of your WORDPRESS install? The following code snippet can allow you to run a WordPress loop on any PHP file, or even outside of your WordPress install.



So just paste the following code on any PHP file where you want to run your WordPress loop for accessing data. So for this you need to modify the following:

line 4: Please specify the path to your WordPress wp-blog-header.php file.
line 5: Query posts using the query_posts() function.

<?php
  // Include WordPress
  define('WP_USE_THEMES', false);
  require('/server/path/to/your/wordpress/site/htdocs/blog/wp-blog-header.php');
  query_posts('posts_per_page=1');
?>

<?php while (have_posts()): the_post(); ?>
   <h2><?php the_title(); ?></h2>
   <?php the_excerpt(); ?>
   <p><a href="<?php the_permalink(); ?>" class="red">Read more...</a></p>
<?php endwhile; ?>


Tuesday, March 12, 2013

How to save bandwidth and reduce server load

How to save bandwidth and reduce server load

1. Use CSS instead of images
2. Always make sure that your images are optimized
3. Use a cache on your website
4. Prevent bandwidth stealing and hotlinking
5. Use Minify to compress CSS and JavaScript files
6. Use hosting websites to host big files
7. Use GZip compression on your PHP files
8. Use a reliable web hosting

Image resizing using jQuery

Image resizing using jQuery

Example of  jquery fixed image resize


$(window).bind("load", function() {
 // IMAGE RESIZE
 $('#product_cat_list img').each(function() {
  var maxWidth = 120;
  var maxHeight = 120;
  var ratio = 0;
  var width = $(this).width();
  var height = $(this).height();
 
  if(width > maxWidth){
   ratio = maxWidth / width;
   $(this).css("width", maxWidth);
   $(this).css("height", height * ratio);
   height = height * ratio;
  }
  var width = $(this).width();
  var height = $(this).height();
  if(height > maxHeight){
   ratio = maxHeight / height;
   $(this).css("height", maxHeight);
   $(this).css("width", width * ratio);
   width = width * ratio;
  }
 });
 //$("#contentpage img").show();
 // IMAGE RESIZE
});
 
 
Source: http://snipplr.com/view/62552/mage-resize/ 


Monday, March 11, 2013

How to make WordPress images responsive

How to make WordPress images responsive

The responsive images can be big on wide screens but automatically adapt to smaller screens such as iphone,iPad. Very easily you can make images responsive. Just follow the simple steps on your blog.


First you have to create the shortcode. Open your functions.php file and paste the following php code in it:

function responsive_images($atts, $content = null) {
     return '<div class="image-resized">' . $content .'</div>';
}

add_shortcode('responsive', 'responsive_images');

Now after that open your style.css file and add those CSS rules:

@media only screen and (max-width:767px) {
    .image-resized img {
        width:100%;
        height:auto;
    }
}

So now you can use the [responsive] shortcode to insert responsive images in your wordpress blog:

[responsive]<img src="image_url" alt="alt" title="title" />[/responsive]

Sql query to delete orphaned post meta from WordPress database

Sql query to delete orphaned post meta from WordPress database

WordPress blog contain thousands of rows of useless meta data. The following simple SQL query can delete orphaned post meta on our database.


You have to just run the following sql query on the WordPress database which delete orphaned post meta.
Before you start, create a backup of your database!

DELETE pm
FROM wp_postmeta pm
LEFT JOIN wp_posts wp ON wp.ID = pm.post_id
WHERE wp.ID IS NULL

Sunday, February 24, 2013

Disable automatic paragraphs in WordPress editor

How to disable automatic paragraphs in WordPress editor

WordPress by default automatically creates paragraphs on the post content. Sometimes this is very useful, but sometimes we might want to change this type of behavior which can fit our specific needs. The following recipe explains how we can disable automatic paragraphs in wordpress.



JUst paste the following line into the theme functions.php file:

remove_filter('the_content', 'wpautop');

Now  Once you saved the file then the WordPress will never create automatic paragraphs on the wordpress post or page content.

Tuesday, January 22, 2013

Shortcode to display external files on Wordpress post

Shortcode to display external files on Wordpress post

While blogging on wordpress, sometimes we may need to include an external file on our post, like text or image etc, into our wordpress posts. Checkout the following a very useful shortcode which embed and display any external files in our wordpress blog posts.


function show_file_func( $atts ) {
  extract( shortcode_atts( array(
    'file' => ''
  ), $atts ) );
 
  if ($file!='')
    return @file_get_contents($file);
}
 
add_shortcode( 'show_file', 'show_file_func' );
 
 
Now use the shortcode like the following example

[show_file file="http://www.thesandip.com/test.html"] 

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off