Learning Is Fun

Talks on Web Technology and Better Product Development

WordPress: adding a custom option box and developing file upload plugin

January15

Hello Buddy,

One of my clients wanted to show thumbnail photo beside the post text as below. So, I had to make a plugin so that the admin can post the thumbnail when he is writing the post or can edit when editing the post. Take a look at the thumbnail’s position below.

Thus, recently I solved a plugin problem in one of my wordpress works although it was small. You know you may sometimes need to add a custom field in your wordpress posting/writing/editing area. To check what I am saying, take a look at the following image:

Adding such a box is extremely easy using the wordpress’s builtin add_meta function. But does file upload works i.e. if you upload the file, will it work? The answer is straight – “NO”. But why? The reason is also simple. If you want to upload a file, your form should have “enctype=”multipart/form-data” in the form opening such as

{code type=HTML}

{/code}

But the problem is – if you open the source code of text editor tool as following,

you will see that it does not have “enctype=”multipart/form-data” unfortunately. It looks exactly like this in my wordpress 2.7 version if I open the wp-admin/edit-form-advanced.php file at line # 520.

{code type=HTML}

{/code}

Not funny? Huh?

So, to cope up with this situation, I had to add “enctype=”multipart/form-data” in the form although I do not like changing the core files. Why do not I like to change the core files? The answer simple. Because whenever there is an update, the client have to update the file everytime. The client may not like it or may even forget it. Anyway, after change, it looks like this:

{code type=HTML}

{/code}

OK. Lemme show you step by step what to do if you want to add a file upload plugin.

Step One: Change the “wp-admin/edit-form-advanced.php” file

Open this file from the mentioned location and change the following line in the file:

{code type=HTML}

{/code}

to this line:

{code type=HTML}

{/code}

Step Two: Write you plugin

Here goes mine:

{code type=PHP}

/*
Plugin Name: Bag Thumbnail
Plugin URI: http://www.tanzilo.com/
Description: This plugin helps you to set thumbnail image of your bags.
Author: Tanzil Al Gazmir
Version: 1.0
Author URI: http://www.tanzilo.com/
*/

function init_bag_review_thumb_widget()
{

global $wpdb;

$result = mysql_list_tables(DB_NAME);
$current_table = array();
while($row = mysql_fetch_row($result))
{
$current_tables[] = $row[0];
}
$myNewDatabaseTable = $wpdb->prefix . ‘bag_thumb’;
if(!in_array($myNewDatabaseTable, $current_tables))
{

mysql_query(”
CREATE TABLE IF NOT EXISTS `” . $myNewDatabaseTable . “` (
`id` int(11) NOT NULL auto_increment,
`post_id` int(11) NOT NULL,
`image_name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
“);
}

/*
// Now I am going to delete all unnecessary thumb images by scanning the
// whole directory
*/
$sqlQuery = “SELECT image_name FROM ” .$wpdb->prefix . “bag_thumb; “;
$fileArray = $wpdb->get_col($sqlQuery);
$fileArray[] = ‘no_thumb.jpg’;

if ($handle = opendir(‘../bag_thumb/’))
{

// This is the correct way to loop over the directory.
while (false !== ($file = readdir($handle)))
{
if(is_file(‘../bag_thumb/’ . $file))
{
if(!in_array($file, $fileArray))
{
unlink(‘../bag_thumb/’ . $file);
}
}
}

closedir($handle);
}

}

// This function tells WP to add a new “meta box”
function add_bag_photo_box()
{

add_meta_box(

‘bag_photo’, // id of the

we’ll add
‘Add Bag Thumbnail Photo’, //title
‘add_bag_photo’, // callback function that will echo the box content
‘post’, // where to add the box: on “post”, “page”, or “link” page
‘normal’,
‘high’

);
}

// This function echoes the content of our meta box
function add_bag_photo()
{
echo

‘;
}

function bag_thumbnail_plugin_save_postdata()
{
$fileArray = array();
global $wpdb;

$file = $_FILES['bag_thumbnail_photo'];
$fileName = $_FILES['bag_thumbnail_photo']['name'];
$basename = ”;

if(!empty($fileName))
{
if(isAllowedExtension($_FILES['bag_thumbnail_photo']['name']))
{

$postID = $_POST['post_ID'];

# Do uploading here
$basename = basename( $_FILES['bag_thumbnail_photo']['name']);
$basename = str_replace(‘ ‘, ‘_’, $basename);
$basename = str_replace(‘-’, ‘_’, $basename);
$basename = strtolower($basename);
$basename = $_POST['post_ID'] . ‘_’ . $basename;
$target_path = ‘../bag_thumb/’;
$target_path = $target_path . $basename;

$sqlQuery = “DELETE FROM ” . $wpdb->prefix . “bag_thumb WHERE post_id=$postID;”;
$wpdb->query($sqlQuery);

move_uploaded_file($_FILES['bag_thumbnail_photo']['tmp_name'], $target_path);

// adding record in the database
$sqlQuery = “INSERT INTO ” .
$wpdb->prefix . “bag_thumb(post_id, image_name)
VALUES($postID, ‘$basename’)”;
$wpdb->query($sqlQuery);
}

}

}

function isAllowedExtension($fileName)
{
$allowedExtensions = array(“png”, “gif”, “jpg”, ‘jpeg’);
return in_array(end(explode(“.”, $fileName)), $allowedExtensions);
}

// This starts whenever the plugin is loaded
add_action(“plugins_loaded”, “init_bag_review_thumb_widget”);

// Hook things in, late enough so that add_meta_box() is defined
if (is_admin())
{
/* Use the admin_menu action to define the custom boxes */
add_action(‘admin_menu’, ‘add_bag_photo_box’);
}

/* Use the save_post action to do something with the data entered */
add_action(‘save_post’, ‘bag_thumbnail_plugin_save_postdata’);

?>
{/code}

Please notice that I dynamically delete any unnecessary file using the PHP’s unlink() function.

Step Three: get your image name from the database

I have placed the following code in my functions.php file.

{code type=PHP}

if(!function_exists('getBagThumbName'))
{
function getBagThumbName($postID)
{
global $wpdb;
$sqlQuery = 'SELECT image_name FROM ' . $wpdb->prefix . ‘bag_thumb WHERE post_id=’ . $postID . ‘;’;
$fileName = $wpdb->get_var($sqlQuery);
$fileName = trim($fileName);
$fileURL = get_option(‘siteurl’) . ‘/bag_thumb/’ . $fileName;
if(!empty($fileName))
{
return $fileURL;
}
else
{
return (get_option(‘siteurl’) . ‘/bag_thumb/no_thumb.jpg’);
}
}
}

?>
{/code}

Step Four: Link with the index.php or single.php or wherever you want

See how I placed the thumbnail image source in the code of index.php and single.php file.

{code type=PHP}

Step Five: Test

Now you need to test and we are done!

You can also download my little plugin if you want from here:
http://www.tanzilo.com/demo/code/bag-thumb/bag-thumb.zip

Thank you for reading.

posted under PHP, Wordpress | 31 Comments »

WordPress: display posts by category ID. Solution with code & example.

January6

Hello Guy!

Often in many blogging sites, you will see two or three columns of the most important categories. Recently I had to do this for a blog. It was a little bit cumbersome and time consuming. So, I would like to share the solution so that you can kill the time waste trying yourself in case you do not know how to do it. In this solution, I show 5 posts at maximum from my chosen three categories.

OK.
Let us start and let me show how to do it.

Step One: See the sample what would be the output

In the above image, you will notice that the first category has enough posts, so it can fetch 5 (five) posts for us. But in second column and third column, there are only three posts because those categories do not have more than three posts. And what I want to say at this point is – although we will try to get 5 posts from each category, we will not get enough in case that category has less than 5 (five) posts and this is done automatically.

Step Two: Adding custom function

{code type=PHP}

if(!function_exists('postListByCategory'))
{
function categoryNameByCategoryID($categoryID = 0)
{
global $wpdb;
$sqlQuery = 'SELECT name FROM ' . $wpdb->prefix . “terms WHERE term_id=$categoryID”;
return $wpdb->get_var($sqlQuery);
}
}

if(!function_exists(‘postListByCategory’))
{
function postListByCategoryID($categoryID = 0)
{
$outputString = ”;
query_posts(‘orderby=name&order=asc&cat=’ . $categoryID . ‘&showposts=5′);
$outputString .= ‘

    ‘ . chr(10);
    while (have_posts()) : the_post();
    $permaLink = get_permalink();
    $permaLink = trim($permaLink);
    if(!empty($permaLink))
    {
    $outputString .= ‘
  • ‘ . chr(10);
    $outputString .= ‘‘ . get_the_title($post->ID) . ‘
    ‘ . chr(10);
    $outputString .= ‘‘ . get_the_time(‘D M jS Y’) .’‘ . chr(10);
    $outputString .= ‘
  • ‘ . chr(10);
    }
    endwhile;
    $outputString .= ‘

‘ . chr(10);
return $outputString;
}
}

?>
{/code}

Now open the functions.php file inside your theme directory and insert these two functions. If there is none, create a functions.php file. And at this point, please remember that all the functions and coding in this file are automatically added during the code execution.

Note that the function names are self descriptive.

Step Three: Embed code in your file(s)

Now open your footer.php file or any other file and add this code. In 99% cases, you may need to customize this small piece of code. The first three lines are category IDs.

{code type=PHP}

$firstColumnCategoryID = 1;
$secondColumnCategoryID = 30;
$thirdColumnCategoryID = 31;

?>

 

 

 

{/code}

Step Four: Link your CSS code

{code type=CSS}
#bottomThreeColumns
{
width:940px; min-height:100px; margin:0 auto; clear:both;
}
#bottomThreeColumns UL
{
margin:0px 0px 30px 0px; padding:0px;
}
#bottomThreeColumns LI
{
list-style:none; border-bottom:#EEEEEE solid 1px; margin:7px 0px 0px 4px;
}
#bottomThreeColumns LI A
{
text-decoration:none; color:#000000;
}
#bottomThreeColumns LI A:hover
{
text-decoration:underline;
}
#bottomThreeColumns SMALL
{
font-style:italic; line-height:25px; padding:0px 0px 0px 4px;
}
#bottomColumn
{
float:left; width:300px; margin:20px 20px 0px 0px;
}
#bottomColumnThird
{
float:left; width:300px; margin:20px 0px 0px 0px;
}
#bottomColumnTop
{
width:300px; height:26px; background:#5FB8EB; color:#FFFFFF;
line-height:25px; font-weight:bold;
}
{/code}

I have put the above CSS code in my style.css file. In 99% cases, you may need to customize according to your requirements.

Step Five: Test everything by opening the link

Now test you code and we are done!

Thank you for reading.

posted under PHP, Wordpress | 9 Comments »

WordPress: get page id and content with example & code

December19

Hey Guys!

Often I see people coming to my site searching with the terms wordpress get page id, wordpress get page content or something similar. I think wordpress developers face situations when they need to get page or post information in customized way. It happened to me too and I would like to share it with others since often people are coming to search this information.

Well. It is very easy and we can solve it quickly.
OK. Now let me show you how to get these information.

Remember one thing that is important for wordpress data fetching of this kind. Your posts and pages information is saved in a single database table and that is wp_posts. The wp_ is the prefix of you database and may differ. But most of the times the database table name is wp_posts and other times it is YourCustomPrefix_posts. We are going to fetch data from this table.

WordPress – print page id:

There is a built-in wordpress function using which you can print the post or page id. When you call this, this directly prints this inforation in your page without the need to use the built-in PHP echo or print function. Remember to keep it in the while loop.

{code type=PHP}


{/code}

WordPress – get page id:

There is a global variable post which contains the related information of the currest post or page. The name of the variable is: $post and it is actually an object. You can access information just as you access variables from an object. Remember to keep it in the while loop.

{code type=PHP}

global $post;
echo $post->ID;
?>


{/code}

You can print all the information in the $post object to see all the variables and their values that is contains.

{code type=PHP}

global $post;
var_dump($post);
?>


{/code}

WordPress – get page content:

Now you know you can get the page or post content from $post->post_content variable. But if you echo or print them, they may look somewhat without formatting. So, you need to use PHP built-in nl2br() function to look the content as it is.

{code type=PHP}

global $post;
echo nl2br($post->post_content);
?>


{/code}

WordPress – get any information of your page or post:

You know you can print all information to check all the available variables and their values through using PHP’s built-in var_dump() function. Suppose you need to get the post title, post type and posting time. We can get them easily in this way.

{code type=PHP}

global $post;
echo $post->post_title;
echo $post->post_type;
echo $post->post_date;
?>


{/code}

Please notice that post_title, post_type and post_date are all several database fields from wp_posts table of our wordpress database.

Very easy. Right? And that is all for getting the page or post information.

Thank you for reading.

posted under PHP, Wordpress | 43 Comments »

WordPress: Custom URL rewrite and reading URL values

December17

Hello!

Recently I was working for a Irish guy who has opened a wordpress blog few months ago. I did the theme for him. Recently he requested me for modifying and/or upgrading the project. One of the project requirements was URL rewriting. For example, there can a URL as follows:
http://www.sitename.com/index.php?group_name=My-Input-Value-Goes-Here

But after rewrite, the URL should look like:
http://www.sitename.com/My-Input-Value-Goes-Here

Well. You see I am passing the variable value in index.php file. But I needed to read the custom URL passed value through another PHP file and that is group.php. My group.php file was inside the theme folder. I am passing the group_name value in index.php file but reading from group.php file. It sounds a bit interesting. Huh?

OK. After browsing several blogs, I came up to writing a custom plugin. Thanks to Google.com and all those people sharing information.

My plugin made me a way so that I could pass a variable value in index.php file but read it from group.php file. This plugin code is available almost everywhere. Here goes my plugin:

{code type=PHP}

/*
Plugin Name: WP Custom URL
Plugin URI: http://www.tanzilo.com/#
Description: A plugin to allow parameters to be passed in the URL and recognized by WordPress
Author: Tanzilo
Version: 1.0
Author URI: http://www.tanzilo.com/
*/

function flush_rewrite_rules()
{
global $wp_rewrite;
$wp_rewrite->flush_rules();
}

function add_rewrite_rules( $wp_rewrite )
{
$new_rules = array(
‘(.+)’ => ‘index.php?group_name=’ .
$wp_rewrite->preg_index(1) );

$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

function add_query_vars( $qvars )
{
$qvars[] = ‘group_name’;
return $qvars;
}

function template_redirect_file()
{
global $wp_query;
if ( $wp_query->get(‘group_name’) )
{
if (file_exists( TEMPLATEPATH . ‘/group.php’ ))
{
include( TEMPLATEPATH . ‘/group.php’ );
exit;
}
}
}

add_action(‘init’, ‘flush_rewrite_rules’);
add_action(‘generate_rewrite_rules’, ‘add_rewrite_rules’);
add_filter(‘query_vars’, ‘add_query_vars’);
add_action(‘template_redirect’, ‘template_redirect_file’);

?>
{/code}

So, what happens now when I activate this plugin? It does a simple work and that is: when it gets a link as below:
http://www.sitename.com/index.php?group_name=My-Input-Value-Goes-Here

It sends the group_name variable value to group.php file which is in the theme folder. In group.php file, I can catch the variable value and use it anyway I want.

Do you want to see my group.php file too? OK. Here it goes:

{code type=PHP}

$group_name = $_GET['group_name'];
$group_name = str_replace('-', ' ', $group_name);

?>

If you enjoyed this post, make sure you
(dot)htaccess file for solving the rest of the part.

I was searching for a helpful blog link and after searching many blogs, I found a similar blog article and here it is:

http://www.webmasterworld.com/forum92/6079.htm

In this blog, I found a similar solution and wrote my own based on this code.

{code type=HTML}
# Enable mod_rewrite, start rewrite engine
Options +FollowSymLinks
RewriteEngine on
#
# Internally rewrite search engine friendly static URL to dynamic filepath and query
RewriteRule ^product/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ /index.php?product=$1&color=$2&size=$3&texture=$4&maker=$5 [L]
#
# Externally redirect client requests for old dynamic URLs to equivalent new static URLs
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?product=([^&]+)&color=([^&]+)&size=([^&]+)&texture=([^&]+)&maker=([^\ ]+)\ HTTP/
RewriteRule ^index\.php$ http://example.com/product/%1/%2/%3/%4/%5? [R=301,L]
{/code}

Finally my (dot)htaccess file looked like this:

{code type=HTML}
# BEGIN WordPress

RewriteEngine On
RewriteBase /

RewriteRule ^pages/([^/]+)/?$ /index.php?group_name=$1 [L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?group_name=([^&]+)\ HTTP/
RewriteRule ^index\.php$ http://mobile.ie/pages/%1? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress
{/code}

But I was not 100% perfect but close to the solution. The reason is my URL started looking like this:
http://www.sitename.com/pages/My-Input-Value-Goes-Here

Well. You see I was almost close to the solution. As the buyer wanted like this:
http://www.sitename.com/My-Input-Value-Goes-Here

But I came up with a solution to:
http://www.sitename.com/pages/My-Input-Value-Goes-Here

I believe you can work on it and come to a solution without the extra “pages/” part in the URL. If you find such a solution, please share with me and others who will face similar problem.

Dude! That is all for now.

Thank you for reading.

posted under PHP, Wordpress | 11 Comments »

WordPress: Upload many PHP files quickly by Zip & Unzip

December15

Hello!

It is actually not only for a wordpress developer but also for all those developers who face situation where they must upload many files to the server. Recently in a wordpress project, I had to upload wordpress 2.7 version files in the server. In the wordpress 2.7 package, you will find around 600 files! Uploading them is not very interesting when your internet connection do not guarantee you smooth upload.

Uploading the 600 files brought me pain because they were going to the server very slowly and each time some files were corrupted and for any reason reuploading the corrupted files were not working. It was really time consuming, boring and painful. Then I started to look for an alternative solution. Then, I naturally came to the idea that how about I zip (compress) the folders containing most of the files and upload them. Thus I have to upload few zip files although bigger in size. Writing a piece of PHP code to unzip the zipped file is easy too.

So, I decided to zip the main three folders and uploaded them. You know they contain most of the files.

OK. Let me tell you the process in step by step way so that you can follow easily:

  1. First I zipped my three folders (wp-admin, wp-content & wp-includes) that contains most of the files.
  2. Changed the ‘public_html‘ folder permission to 777. Remember you will do it for the folder where you are going to upload.
  3. Uploaded the three zipped folders.
  4. Run my PHP script that you will see below.
  5. Checked if everything is OK and found them OK.
  6. Changed the file permission of the ‘public_html‘ folder back to 750. If you uploaded to any other folder, you need to change the permission 777 to any combination you think good for your purpose.
  7. Deleted the zip files since they are no longer required.

Here goes my PHP code to unzip them and it is very simple!

{code type=PHP}

$zipFileNames = array();
$zipFileNames[] = 'wp-admin.zip';
$zipFileNames[] = 'wp-content.zip';
$zipFileNames[] = 'wp-includes.zip';
// and all other zip files

$indexLimit = count($zipFileNames);
for($i=0; $i<$indexLimit; $i++)
{
$fileLink = $_SERVER['DOCUMENT_ROOT'] . '/' . $zipFileNames[$i];
if(is_file($fileLink))
{
if(exec("unzip $fileLink"))
{
echo 'Successful! ' . $fileLink . ' is properly unzipped!' . '
‘;
}
else
{
echo ‘Failed! exec() failed to execute as expected!’ . ‘
‘ .
‘Please check if the directory permission is 777 where you are trying upload.’;
}
}
else
{
echo ‘Error: ‘ . $fileLink . ‘ is not a (zip) file!’ . ‘
‘;
}
}

?>
{/code}

By the way, you can improve the code to more sophisticated one as per your requirement. For example, the exec() function has several options that you can use for more flexibility or anyway anything else you want.

Oh! There is one other way to unzip a uploaded zipped file although I did not use this piece of code. But remember that if you use this code you need to set your destination file permission to ’777′ first and then change as mentioned before after you unzipped. Fortunately this coding is very simple too and an example is as follows:

{code type=PHP}

$zip = new ZipArchive;

if($zip->open($_SERVER['DOCUMENT_ROOT'] . ‘/hello.zip’) === true)
{
$zip->extractto($_SERVER['DOCUMENT_ROOT'] . ‘/hellotest/’);
$zip->close();
echo ‘Files successfully unzipped!’;
}
else
{
die(‘Failed to open zip file’);
}

?>
{/code}

I tested both the processes mentioned above in Linux system and not sure how it works in Windows Server. I guess the second process should work in Windows server for uploading and unzipping bulk file quickly.

This is all for the trick of the game and for killing the pain of uploading several hundred of files.

Well. You can download my little sweet code here too:
http://www.tanzilo.com/demo/code/unzip/unzipping.zip

Thank you for reading.

posted under PHP, Wordpress | 2 Comments »

Flash swf and Lightbox overlapping problem solution

December13

Recently I was working in an American project where my client wanted to convert this static site to dynamic. Everything was fine except the gallery. The existing gallery was done using Lightbox effect and there was a flash audio file. The audio file was avoiding the Lightbox effect and coming overlapping any effect. And this is where the problem started.

OK. See below for an idea how it looked:

Not funny or interesting. Ugly, Huh? So, my client requested to fix it.

But what is the reason for this problem? Hm? Actually this was happening because Flash file is always above any other elements in your page. It comes at the topmost priority position in your page and that is why it can ignore the Lightbox effect. Our job is to make sure taht the Flash swf file stands behind the door when a Lighbox effect is in action. Clear?

In few blogs, I found possible solutions and they did not work. One possible solution that I thought would work was using z-index property in CSS. One coder advised to keep the embedding code in a lower z-index (such as 0) and keeping the container gallery in higher z-index (such as 1). Although he said, it worked for her, but did not work for me. But you can give a try if you want. May be this trick can work for you depending you code.

So, how did you fix it so that it looks like as follows?

So, what is the trick?  If you make sure that you added the following lines bold red in your HTML code, the problem is solved.

<?php
$client_testimonial = “/testimonials/audio_file.mp3″;
?>
<object type=”application/x-shockwave-flash” width=”200″ height=”15″
data=”/testimonials/xspf_player_slim.swf?song_url=<?php echo $client_testimonial; ?>&song_title=Air-trekkers Testimonial&player_title=Click to hear testimonial!”>
<param name=”wmode” value=”opaque”>
<param name=”movie”
value=”/testimonials/xspf_player_slim.swf?song_url=<?php echo $client_testimonial; ?>&song_title=Air-trekkers Testimonial&player_title=Click to hear testimonial!” />
<embed wmode=”opaque” src=”/testimonials/xspf_player_slim.swf?song_url=<?php echo $client_testimonial; ?>&song_title=Air-trekkers Testimonial&player_title=Click to hear testimonial!” quality=”high” pluginspage=”http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash” type=”application/x-shockwave-flash” width=”200″ height=”15″></embed>
</object>

That is all and…

Thank you for reading.

posted under AJAX, PHP, Wordpress | 22 Comments »

WordPress: Creating a Static Front/Home Page without Plugin

November28

Hello WordPress Developer!

When I was new to wordpress blog devevelopment, I got few projects where the clients wanted a static homepage and a Blog link in the menu. In some other projects, the clients wanted to make the homepage to be semi dynamic; that means in the homepage we will show some wordpress data like three latest posts and other things will be static.

You know when we install WordPress the homepage is by default going to show the latest 10 blog entries. But now the homepage will be static, semi dynamic or anything. We will create a page and link it to default WordPress homepage.

OK. Take a look below of what I mean.

I tried it several ways. But I was not satisfied the available solutions. But luckily I figured out a stable solution. My solution does not need any plugin and it is simple too.

Step One: Create your custom homepage

First of all create your homepage as static, dynamic or whatever you want name it as home.php and remember that when visitors come to your site, they will see this file running as front page or website homepage. Upload it in the theme directory.

Step Two: Create your blog homepage templae

Create your blog homepage template and name it blog.php or anything. For clarity and relevance, let us name it blog.php and upload it in the theme directory.

Here is the code:

{code type=PHP}
/*
Template Name: Blog
*/

// Which page of the blog are we on?
$paged = get_query_var('paged');
query_posts('cat=-0&paged='.$paged);

// make posts print only the first part with a link to rest of the post.
global $more;
$more = 0;

//load index to show blog
load_template(TEMPLATEPATH . '/index.php');
?>
{/code}

Step Three: Create your blog homepage

Now create your blog homepage index and name it as index.php and then upload it in the theme folder.

Here is a sample of blog index.php file code:

{code type=PHP}

” rel=”bookmark” title=”Permanent Link to “>

show_photos(); ?>


{/code}

Upload this new falbum.php file to your theme directory in the server.

Please remember that there are two different falbum.php files in two different locations. So, pleaes do not confuse with one another.

instllation_directory/wp-content/plugins/falbum/falbum.php
instllation_directory/wp-content/themes/theme_name/falbum.php

We have created the second one from our theme’s index.php file.

Step Seven: Check the output

Go to your website, refresh it twice and click on the thumbnail of any flirkr image.

So, you are done. Huh?

Integrating a complete gallery in wordpress

Well. You may want to keep a single page as your album home and in that page you may want to keep some Flirkr photos in thumbnail so that it looks gallery homepage. Fine!

Now let us see how we can do this.

Step One: Read the above part “Integrating a small gallery in wordpress”

Check the above part thoroughly since you will need the knowledge from the above part titled as Integrating a small gallery in wordpress. Since many things are common, I have avoid the repeated description.

Step Two: create a file and link it to wordpress

First of all, create a file and link it with wordpress. You can follow my another article to do this. The another article is here:

http://www.tanzilo.com/2008/11/02/wordpress-how-to-add-and-link-static-or-custom-pages/

Step Three: add the album code to your page

You can add photos in several ways. For example, if you want to add latest or recent 8 photos, add the following code.

{code type=PHP}
show_recent(8); ?>
{/code}

If you want to show 8 random Flickr photos, add code like this:

{code type=PHP}
show_random(8); ?>
{/code}

You will find more details on how to customize your page in the following link:
http://www.randombyte.net/wiki/falbum/functions_and_variables

Step Four: Customize CSS coding for custom look

Remember that each thumbnail photo will be placed in a list element. So, if this is the PHP code where we place the album:

{code type=PHP}
require_once(ABSPATH.'/wp-content/plugins/falbum/falbum.php');
global $falbum;
echo $falbum->show_recent(6);
?>
{/code}

Here is the CSS to make them looking like a thumbnail gallery:

{code type=CSS}
#footerFlickrPhotos
{
width:323px; margin:23px 0px 0px 48px; float:left;
}
#footerFlickrPhotos UL
{
margin:0px; padding:0px;
}
#footerFlickrPhotos LI
{
list-style:none; float:left; margin:0px; padding:0px;
background:none;
}
#footerFlickrPhotos IMG
{
width:75px; height:75px; border:#FFFFFF 2px solid;
float:left; margin:5px 15px 10px 0px;
}
{/code}

Next, the bigger photo and all other things like next, previous buttons and tags etc will be displayed in a DIV element named as content.

{code type=CSS}
#content
{
width:580px;
}
#content A
{
color:#0B4B93; text-decoration:none;
}
#content A:hover
{
text-decoration:underline;
}
{/code}

Step Five: Check your site

Now you are done! Go to your site, refresh the site twice and check you album.

So, we are done!

These following two links will be helpful and you can visit them for more information:
http://www.randombyte.net/wiki/falbum/functions_and_variables
http://www.randombyte.net/wiki/falbum/incorporating_falbum_into_your_own_theme

Thank you for reading.

posted under PHP, Wordpress | 6 Comments »

WordPress: How to add and link static or custom pages

November2

When I was new to wordpress theme development, I faced a common problem that many others might have faced. That is adding or linking or integrating a static or custom page in your wordpress site. It is very possible that you may prefer to keep one of your page or file linked as the following:

http://www.yoursitename.com/products.php

Sometimes this kind of requirement arrive that you have no other option but to do it.

But you know this kind of link will not directly appear in your wordpress blog or site because of the unique linking structure of wordpress. Most probably you will get a 404 error i.e. file not found error. So, if you want to link directly, you need to follow a simple trick. This trick is simple, small and intereting.

If you want to add and link your custom or static pages, follow these steps and you will get smooth result:

Step One: Changing the header of the php file

In this article, we will add a php file products.php in our wordpress blog. So, please create your products.php file.  Now open you products.php file and add the following two lines at the top of the file and save your file.

{code type=PHP}
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
?>
{/code}

Remember, these lines will be the topmost lines in your products.php file. OK? See below how I added.

{code type=PHP}
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
?>





{/code}

Why are we adding these two lines? Because we are telling wordpress that this file will not use wordpress themes and we are going to link it in a different way. So, wordpress do not force to link in its usual way.

Step Two: Saving in the public_html or root folder

Now upload it in the wordpress installation directory so that it looks like:

http://www.yoursitename.com/products.php

Done? Great!

Step Three: Linking the products.php file in a usual way

Now in the code of any wordpress file where you want to link your products.php file, keep the html linking as usual or what we say relative linking. For example, in the contact us page, I am creating such a link in the body section:

{code type=HTML}

Our Products

{/code}

And yes! We are done!
Test now if it works for you.

Thus, you can add any number of pages in your wordperss site. I do not know exactly when you may need to link this way. I had to do it time to time depending on the client’s project requirement.

Thus, you can also protect your pages from permalink (dot)htaccess in wordpress.

Thanks for reading.

posted under Blog, PHP, Wordpress | 15 Comments »

WordPress: get page content by page id. Static pages to Dynamic

November1

Hello!

Recently I am working in a wordpress project where I am converting a total static site to wordpress site. What I do is: (1) from the static pages, I am taking the static text and creating a new wordpress page for each static page. (2) fetching the page content/text by page id and (3) showing them wherever I want.

I have written a function and now I can fetch the content of any page or one more pages just by the page id.

{code type=PHP}

if(!function_exists('getPageContent'))
{
function getPageContent($pageId)
{
if(!is_numeric($pageId))
{
return;
}

global $wpdb;
$sql_query = 'SELECT DISTINCT * FROM ' . $wpdb->posts .
‘ WHERE ‘ . $wpdb->posts . ‘.ID=’ . $pageId;
$posts = $wpdb->get_results($sql_query);

if(!empty($posts))
{
foreach($posts as $post)
{
return nl2br($post->post_content);
}
}
}
}

?>
{/code}

I am using this function to fetch several page data and show them in one page. In the static site, there are several section with different designs. The client want edit each section using wordpress. So, if there are three different sections, I am creating three individual pages for this single page. Next, I am just fetching the content of the three pages by calling my method three times with different parameters and showing the output in one page.

For exampe,

{code type=PHP}

{/code}

Thus, I am just shifting all text and/or content of the static site to wordpress so that the client can edit the site himself. I think this is a simple way or technique if you want to convert your static page to dynamic wordpress site.

You can also customize this one as per your need. For example, you may only need to fetch the page title.

{code type=PHP}

if(!function_exists('getPageTitle'))
{
function getPageTitle($pageId)
{
if(!is_numeric($pageId))
{
return;
}

global $wpdb;
$sql_query = 'SELECT DISTINCT * FROM ' . $wpdb->posts .
‘ WHERE ‘ . $wpdb->posts . ‘.ID=’ . $pageId;
$posts = $wpdb->get_results($sql_query);

if(!empty($posts))
{
foreach($posts as $post)
{
return nl2br($post->post_title);
}
}
}
}

?>
{/code}

You can not only get the page content, but also the post content if you set the value of the “$pageId” equals any post id. You know you can see the page or post id from the admin panel.

By the way,
I have put my functions in the functions.php file so that I can access it from anywhere. I suggest you following the same way i.e. writing all your custom functions in the functions.php file.

Thank you for reading.

posted under Blog, PHP, Wordpress | 45 Comments »
« Older Entries