feed me feed me chillireward

By Tag Wordpress Tweaks

Reverse Order in comments

 

Most wordpress themes (nearly all of them) display comments in an ascending order. That is the first comment is on top and the latest at the bottom of the page. If you are anything like me and want to dig into the latest comment right away, you would prefer a reverse ordering of comments. This is a preferred approach in popular blogs, as otherwise you have to literally scroll down zillions of comments, to finally reach the latest..

onetwothree

While achieving this in PHP is childs play, accessing a couple of functions in WP took some hunt and peck approach. I finally managed to locate the important functions that would get us the desired look.

So the magic functions are :

get_comments_number();


array_reverse($comments,true);

get_comments_number() returns the total number of approved comments.
array_reverse($comments,true) queries for comments and returns them in reverse chronological order. Thank you Verne for this!
All we have to do is bring the above two together, and voila, you get a numbered, reverse ordered comment system..

18th Jan 2008: Yikes! There is a mistake in the code, I gave yesterday. I incremented the comment count, which was not needed. The culprit was the $comments_count–; variable that I called before displaying the comment. I apologise to anyone who borrowed the code, in blind faith.

    The steps are:

  1. Get total comments
  2. Show comments
  3. reduce comment counter, as we are counting downwards.

Here is the code for the same with suitable comments..

<?php if ($comments) : ?>
<div class="displaycomments">
<h3 class="shdr">
     <?php comments_number(,‘My very first comment<span class="exclamation">!</span>’,‘ <span class="totalnumber">%</span> opinions <span class="exclamation">!</span> <small>(recent->oldest)</small>’);
     ?>
     </h3>

<?php
/* get the total number of comments  */
$comment_count=get_comments_number();

/* get the comments in reverse order */
$comments = array_reverse($comments, true);

/*show the comments one by one*/
foreach ($comments as $comment) :

/*this determines whether comment is direct comment or a trackback from another blog */
$comment_type = get_comment_type();
$isByAuthor = false;

/* checking to see if e-mail is authors [for different styling purpose]
the variable, $oddcomment has values ‘alt’ AND ‘def’ which help style the CSS classes for alternate look in comment display */

if(($comment->comment_author_email == ‘lmareddy@yahoo.com’)||($comment->comment_author_email == ‘lak@mareddy.com’)) {
     $isByAuthor = true;
     $oddcomment = ‘auth’;
     }
     elseif (‘alt’ == $oddcomment && $isByAuthor == false) $oddcomment = ‘def’;
     else $oddcomment = ‘alt’;

/*checking to see if the number is single digit.  If yes, add a zero before it to display stylishly.*/
if (strlen($comment_count)==1) {$comment_count = ‘0′.$comment_count;}
     ?>

<div class="comment" id="comment-<?php comment_ID() ?>">
               <span class="commentdatetime"><?php comment_date(‘d M Y’) ?><em><?php comment_time()?></em></span>

<!– this is the class that decides styling for author/alternate styles –>
<div class="<?php echo $oddcomment; ?>">

     <span class="commentnum"><?php echo $comment_count;?></span>     

<!– the following is the mygravatar part which shows photos of commentors–>             
     <div class="mygravatarwrap"><div class="mygravatars">
     <?php if(function_exists(‘autoavatar’)){ autoavatar(‘http://chilligavva.com/avatars/defavatar.png’,‘Check out my myBlogLog profile!’,‘Click and make yourself a gravatar!’);}?>
     </div></div>   
<!– end photo part –>                                

<div class="thecomment">      
     <span class="commentauthor"><em><?php comment_author_link(); ?></em> said</span>
<?php edit_comment_link(__("Edit"), ‘ ? ‘, ); ?>     
<?php comment_text() ?>
</div>

<!– end altcomment –>  </div>
<!– end comment –></div>

<?
/*lets now reduce the comment number by one, as we are counting downwards..*/
$comment_count–;
?>
<?php endforeach; /* end for each comment */ ?>
<!– end displaycomments –></div>
 

Get Path

 

One cannot call an image directly in wordpress in your theme files. For instance I cannot actually place an image with the command

<img src="images/imagename" width="300" height="200" border="0" alt="this is an image"/>

When the page is displayed, nothing happens. This is because of WP taking into account the complete URL and not just referential paths. By providing the correct URL, it would make the task simple. The function getpath(); gets the full base path using the builtin wordpress “TEMPLATEPATH” function. It then substitutes the base path with the URL.

<?php
/*
Plugin Name: Getpath
Version: 1.0
Description: Gets actual path and replaces it with correct url path.
Author: Lakshmi Mareddy
Author URI: http://www.chilligavva.com/about
*/

function getpath(){
$path=TEMPLATEPATH;
/*
‘/home/public_html/<sitename.com>’ is the base url of your blog.
To determine your base url, save the following code in your WP theme directory, in your header.php after <body> declaration and view your site.  Copy the code you see in red, and place it within the quotes of  the string replace line.
Code to check your base url: <h1 style=’color:red;’><? echo TEMPLATEPATH;?>

</h1>
*/
$newloc = str_replace("/home/public_html/<sitename.com>", "http://sitename.com/", $path);
/*~ the following shows correct path string in local server*/
$newloc = str_replace("C:\\apacheserver\\base\\", "http://localhost/", TEMPLATEPATH);
echo $newloc;
}?>
 

Explanation:

The function captures the absolute path generated by “TEMPLATEPATH”, wordpress function into the variable $newloc.

If you notice ethere are two defintions for the same variable $newloc. Depending on whether its a local server or blog server, the correct combination is loaded into the variable.

The paths explained

Local Sever: If the root directory defined in your local server is located at “c:\apacheserver\base” that is what you will write within quotes in the plugin. Note the two left slant lines. They arre escape quotes for the left slant of windows style file location.

Saving into your plugin directory

1. Enter correct base urls for both local and blog servers in the function.
2. Save the code as “getpath.php”and place it in your plugin directory.
3. Activate it via the admin panel of wordpress.

Calling the function

Whenever you want to invoke an image from the /images directory of your theme, you call it thus:

<img src="<?getpath();?>/images/imgname.jpg"/>

Dynamic homepage based on interestingness

 

I am pretty tired of blogs that have ‘n’ number of posts aired on their landing page with a column of info on either side. That was one of the the reason I rehauled my site. I now have a situation wherein the latest 2 posts are displayed on the homepage, and if there is an announcement, the latest single post and the announcement is displayed. Its not rocket science, and its pretty easy to implement..

AIM: If there is an announcement, show only one post from theblog, otherwise show 2 posts.
THINGS TO TAKE CARE: Since I am using float boxes to show the posts, if there is a single post, the corresponding header “the latest from the blog” , and the read more article link should be within the float. When we show 2 posts, the header should be above both the posts and the “read more articles ” should be below the posts, after clearing the floats.
Click on the figure below, to get an idea.

pic to demonstrate conditional display with an announcement..

In the last week of october, I had talked about slicing your WP pages into manageable file chunks. In the example below, the “inc_showsinglepost.php” refers to the display of a single post. Note how I call it within any loop I use. I dont have to be bothered about what is displayed, as I have set the content to show an excerpt everywhere, and all content when shown in a single page.

$post = "";
$anyannouncement="no";
     query_posts(’cat=35 &amp; showposts=1′);
          if (have_posts()) :
          $post = $posts[0];
          while (have_posts()) : the_post();
       $goAwayDate = time() - (60 * 60 * 24 *10);
          $postDate = get_the_time(’U');
          if($postDate < $goAwayDate) {
          } else {
          ?>
<p class="half">

endwhile; endif;
      ?>

     $post=""; $count=0;
     if ($anyannouncement=="yes") {query_posts("cat=-35"."&amp; showposts=1");  }
     else {query_posts("cat=-35"."&amp; showposts=2");  }
     if (have_posts()) :
     ?>
<p class="lilnotes thelatestblogpost">absolutely the latest post</p>
<p class="half"> </p>

<p class="lilnotes thelatestblogpost">absolutely the latest post

<a href="http://www.chilligavva.com/wp-admin/%3C?php%20echo%20get_settings%28%27home%27%29;%20?%3E/index.php/category/general" class="more-entries">read more articles?</a>

<p class="clear">

<a href="http://www.chilligavva.com/wp-admin/%3C?php%20echo%20get_settings%28%27home%27%29;%20?%3E/index.php/category/general" class="more-entries">read more articles?</a>
<p class="clear"> </p>
<p class="clear"> </p>
 

I check to see whether there is an announcement. if there is, I also check to see if its less than 10 days old. Only then, the announcement will be showed. Otherwise, the variable “$anyannouncement” is set to “no”. Then 2 latest posts are showed in the home page. Since the entire code is my “home.php” file, it is what is showed in the home or landing page..

Random Anything

 

Do you like the idea of flipping pictures? I do. I think it creates a nice feeling of freshness without too much investment in creating content. Its actually very easy to implement..
step1: create a folder in the images folder of your current theme directory. Lets say you call it “rotimages” [ yourwpdirectory / wp-content / themes / currenttheme / images / rotimages]
step2: copy all the images you want to display into the above directory. [make sure that they are all equal in height and width for display evenness.]
step3: copy the script from below and save it as “imgrot.php” and place it into the directory you created [ref. step 1]

<?php
/*
        AUTOMATIC IMAGE ROTATOR
     Version 2.2 - December 4, 2003
     Copyright (c) 2002-2003 Dan P. Benjamin, Automatic, Ltd.
     All Rights Reserved.

     http://www.hiveware.com/imagerotator.php
     http://www.automaticlabs.com/

     DISCLAIMER
     Automatic, Ltd. makes no representations or warranties about
     the suitability of the software, either express or
     implied, including but not limited to the implied
     warranties of merchantability, fitness for a particular
     purpose, or non-infringement. Dan P. Benjamin and Automatic, Ltd.
     shall not be liable for any damages suffered by licensee
     as a result of using, modifying or distributing this
     software or its derivatives.

     ABOUT
     This PHP script will randomly select an image file from a
     folder of images on your webserver.  You can then link to it
     as you would any standard image file and you’ll see a random
     image each time you reload.

     When you want to add or remove images from the rotation-pool,
     just add or remove them from the image rotation folder.

     VERSION CHANGES
     Version 1.0
          - Release version

     Version 1.5
          - Tweaked a few boring bugs

     Version 2.0
          - Complete rewrite from the ground-up
          - Made it clearer where to make modifications
          - Made it easier to specify/change the rotation-folder
          - Made it easier to specify/change supported image types
          - Wrote better instructions and info (you’re them reading now)
          - Significant speed improvements
          - More error checking
          - Cleaner code (albeit more PHP-specific)
          - Better/faster random number generation and file-type parsing
          - Added a feature where the image to display can be specified
          - Added a cool feature where, if an error occurs (such as no
            images being found in the specified folder) *and* you’re
            lucky enough to have the GD libraries compiled into PHP on
            your webserver, we generate a replacement "error image" on
            the fly.

    Version 2.1
        - Updated a potential security flaw when value-matching
          filenames

    Version 2.2
        - Updated a few more potential security issues
        - Optimized the code a bit.
        - Expanded the doc for adding new mime/image types.

        Thanks to faithful ALA reader Justin Greer for
        lots of good tips and solid code contribution!

     INSTRUCTIONS
     1. Modify the $folder setting in the configuration section below.
     2. Add image types if needed (most users can ignore that part).
     3. Upload this file (rotate.php) to your webserver.  I recommend
        uploading it to the same folder as your images.
     4. Link to the file as you would any normal image file, like this:

               <img src="http://example.com/rotate.php" />

     5. You can also specify the image to display like this:

               <img src="http://example.com/rotate.php?img=gorilla.jpg" />

          This would specify that an image named "gorilla.jpg" located
          in the image-rotation folder should be displayed.

     That’s it, you’re done.

*/

/* ————————- CONFIGURATION ———————–

     Set $folder to the full path to the location of your images.
     For example: $folder = ‘/user/me/example.com/images/’;
     If the rotate.php file will be in the same folder as your
     images then you should leave it set to $folder = ‘.’;

*/

     $folder = ‘.’;

/*   

     Most users can safely ignore this part.  If you’re a programmer,
     keep reading, if not, you’re done.  Go get some coffee.

    If you’d like to enable additional image types other than
     gif, jpg, and png, add a duplicate line to the section below
     for the new image type.

     Add the new file-type, single-quoted, inside brackets.

     Add the mime-type to be sent to the browser, also single-quoted,
     after the equal sign.

     For example:

     PDF Files: $extList[’pdf’] = ‘application/pdf’;
        CSS Files:  $extList[’css’] = ‘text/css’;

    You can even serve up random HTML files:
         $extList[’html’] = ‘text/html’;
         $extList[’htm’] = ‘text/html’;

    Just be sure your mime-type definition is correct!
*/

    $extList = array();
     $extList[‘gif’] = ‘image/gif’;
     $extList[‘jpg’] = ‘image/jpeg’;
     $extList[‘jpeg’] = ‘image/jpeg’;
     $extList[‘png’] = ‘image/png’;

// You don’t need to edit anything after this point.

// ——————— END CONFIGURATION ———————–

$img = null;

if (substr($folder,-1) != ‘/’) {
     $folder = $folder.‘/’;
}

if (isset($_GET[‘img’])) {
     $imageInfo = pathinfo($_GET[‘img’]);
     if (
         isset( $extList[ strtolower( $imageInfo[‘extension’] ) ] ) &amp;&amp;
        file_exists( $folder.$imageInfo[‘basename’] )
    ) {
          $img = $folder.$imageInfo[‘basename’];
     }
} else {
     $fileList = array();
     $handle = opendir($folder);
     while ( false !== ( $file = readdir($handle) ) ) {
          $file_info = pathinfo($file);
          if (
              isset( $extList[ strtolower( $file_info[‘extension’] ) ] )
          ) {
               $fileList[] = $file;
          }
     }
     closedir($handle);

     if (count($fileList) > 0) {
          $imageNumber = time() % count($fileList);
          $img = $folder.$fileList[$imageNumber];
     }
}

if ($img!=null) {
     $imageInfo = pathinfo($img);
     $contentType = ‘Content-type: ‘.$extList[ $imageInfo[‘extension’] ];
     header ($contentType);
     readfile($img);
} else {
     if ( function_exists(‘imagecreate’) ) {
          header ("Content-type: image/png");
          $im = @imagecreate (100, 100)
              or die ("Cannot initialize new GD image stream");
          $background_color = imagecolorallocate ($im, 255, 255, 255);
          $text_color = imagecolorallocate ($im, 0,0,0);
          imagestring ($im, 2, 5, 5,  "IMAGE ERROR", $text_color);
          imagepng ($im);
          imagedestroy($im);
     }
}

?>

step 4: you can call the random images either directly or as a background picture.

<!– call the file instead of the picture –>
<img src="/images/rotimages/imgrot.php" />

/*call it instead of the picture, in the background declaration..*/
.rotpic {background:url("images/rotimages/imgrot.php") no-repeat;}

Thats it, you are set…

Organizing your theme folder

 

Hello, its wednesday again.. Happy Halloween.! Today, I shall be giving out a tip on how to organize your theme folder, in wordpress so as to get a grip on what you are doing. This is not so much wordpress, as more of a best practice..

Don’t insert your entire code into your sidebar.php, header.php, home.php, page.php, single.php pages… Instead work with chunks.. What do I mean? I shall demonstrate by example.. If you look into my header.php file in my theme folder for chilligavva.com, here’s what you can see after the <body> tag..

This is a slimmer method, and allows me to see what I am doing.. The slicing does not affect the page generation, but is more of a behind the scenes way of allowing you to break down your theme into manageable chunks.. For instance, the baby blocks i am working with is “inc_geoscript.php” and “inc_aboutblog.php”. Note the way I included the file(s). Its preceded by a TEMPLATEPATH location. This way, you can manage any theme or reuse theme iles without typing out oh so long web addresses.. Neat huh?

Hope this was of some use to you…
Grab the sample here…

<body id="top">
<div class="outerwrap"><div class="ctr">     
<a href="#rsslist" class="rss"></a>
     <?php include (TEMPLATEPATH.‘/inc_searchform.php’); ?>
     <div class="logo"><h1><a href="<?php echo get_settings(‘home’); ?>">Chilligavva</a></h1></div>
     <div class="hdr ">
          <? include (TEMPLATEPATH.‘/inc_heading.php’); ?>
          <? if (is_home()){?><div class="whereufrom"><?php include (TEMPLATEPATH.‘/inc_geoupscript.php’); ?></div><?}?>
          <!– end header –></div>
          <div class="clear"> </div>
     <? include (TEMPLATEPATH.‘/inc_menu.php’); ?>     
     <div class="clear"> </div>

     <!– begin content –>
<noscript><p class="noscript">OOPS!  Some parts of Chilligavva <em>will not work without JavaScript enabled</em>.Please, <em>enable JavaScript in your browser</em> and reload the page.  <em>It will not harm your system. That’s a promise.</em></p></noscript>
     <? if (is_home()){ ?>    <? include (TEMPLATEPATH.‘/inc_aboutblog.php’); ?>     <? }?>
 

Managing state in wordpress

 

Sometimes we want to display a different button for when you are logged-in and another for when you are not.. (See pictures)
Login button example
logout button example

/*we figure out if user is logged in?  If not logged in, show <login> button, else show <logout> button */

     a href=’/ wp-login.php”target=“new” class=“login”> login

     <a href="http://chilligavva.com/wp-admin/%E2%80%9C%3C">/ wp-login.php?action=logout” target=“new” class=“logout”> logout </a>

     <br clear="“all”" />
</logout></login>

Instead of styling the link classes, you can also just change the text message to say whatever you want.