WordPress : WP_Query vs query_posts() vs get_posts() [Differences |Comparison]


WP_Query vs query_posts() vs get_posts()

  • query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use ofpre_get_postshook, for this purpose. TL;DR don’t use query_posts() ever;

  • get_posts() is very similar in usage and accepts same arguments (with some nuances, like different defaults), but returns array of posts, doesn’t modify global variables and is safe to use anywhere;

  • WP_Query class powers both behind the scenes, but you can also create and work with own object of it. Bit more complex, less restrictions, also safe to use anywhere.

 

Image

Source 

For WordPress News Website in local languages, contact me.

For customized web applications, websites using PHP codeigniter, contact me.

Advertisements

Create image in PHP using GD with different font , size (Using ttf fonts)


It is going to be pretty basic tutorial. I am gonna write the advanced or the other ones in the next tutorials. Here is a simple code in php which creates a image on the fly. This code is so simple,but i have written comment before each line to help you understand the flow of the code.

//creates a image handle
$img = imagecreate( 200, 200 );
 
//choose a bg color, u can play with the rgb values
$background = imagecolorallocate( $img,232, 0, 135 );
 
//chooses the text color
$text_colour = imagecolorallocate( $img, 255, 255, 255 );
 
//sets the thickness/bolness of the line
imagesetthickness ( $img, 3 );
 
//draws a line  params are (imgres,x1,y1,x2,y2,color)
imageline( $img, 20, 130, 165, 130, $text_colour );
 
//pulls the value passed in the URL
$text = $_GET['days'];
 
// place the font file in the same dir level as the php file
$font = 'comic.ttf';
 
//this function sets the font size, places to the co-ords
imagettftext($img, 100, 0, 11, 120, $text_colour, $font, $text);
//places another text with smaller size
imagettftext($img, 16, 0, 10, 160, $text_colour, $font, 'Small Text');
 
//alerts the browser abt the type of content i.e. png image
header( 'Content-type: image/png' );
//now creates the image
imagepng( $img );
 
//destroys used resources
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $img );
Image

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>’;

}

Watermark images using php


<?php 

// this script creates a watermarked image from an image file – can be a .jpg .gif or .png file 

// where watermark.gif is a mostly transparent gif image with the watermark – goes in the same directory as this script 

// where this script is named watermark.php 

// call this script with an image tag 

// <img src=”watermark.php?path=imagepath”> where path is a relative path such as subdirectory/image.jpg 

$imagesource =  $_GET[‘path’]; 

$filetype = substr($imagesource,strlen($imagesource)-4,4); 

$filetype = strtolower($filetype); 

if($filetype == “.gif”)  $image = @imagecreatefromgif($imagesource);  

if($filetype == “.jpg”)  $image = @imagecreatefromjpeg($imagesource);  

if($filetype == “.png”)  $image = @imagecreatefrompng($imagesource);  

if (!$image) die(); 

$watermark = @imagecreatefromgif(‘watermark.gif’); 

$imagewidth = imagesx($image); 

$imageheight = imagesy($image);  

$watermarkwidth =  imagesx($watermark); 

$watermarkheight =  imagesy($watermark); 

$startwidth = (($imagewidth – $watermarkwidth)/2); 

$startheight = (($imageheight – $watermarkheight)/2); 

imagecopy($image, $watermark,  $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight); 

imagejpeg($image); 

imagedestroy($image); 

imagedestroy($watermark); 

?>

The script centers the watermark, but can easily be modified to place it along any edge if you would prefer a different location.   For example removing the “/2” in the $startwidth and $startheight variable calculations will put the watermark in the lower right corner. 

You can then make the original images inaccessible if you put the following lines in a .htaccess file in the directory with the images: 

RewriteEngine On
RewriteCond %{REQUEST_URI} !error.gif$
RewriteRule .(gif|jpg|png)$ /error.gif [L] 

This will redirect any attempt to directly access an image in that directory to the error image specified.   Note that the error image is specified on two lines in the .htaccess file.   The first line allows the error image to bypass the rewrite.