On a client site I’m currently developing in WordPress, I’m having to add the client’s existing articles to the new site, as well as his old blog. I wanted them to both exist as Posts, but to be separated within the site. Most of that was straightforward – by assigning articles and blog posts to their own Post Categories, I was able to only include, say, Posts from ‘Category #1′ on the Articles page, and Posts from ‘Category #2′ on the blog page.

Where I came a little unstuck was the Search feature in WordPress. No matter which page I searched from, I would be given the relevant results from all Posts, not just the Category in question. So here’s how I went about fixing that…

Firstly, I added the following Search form to my sidebar:

<form id="searchform" action="<?php bloginfo('home'); ?>/" method="get">
<input id="s" maxlength="96" name="s" size="18" type="text" value="Search" />
<input name="site_section" type="hidden" value="blog" />
<input id="searchsubmit" class="hidden" type="submit" value="Search" />
</form>

Note the third line, with the hidden input (that’s the third line if you paste that into a code editor, not what shows up here). On the sidebar for the blog, I gave that input field a value of ‘blog’; for the sidebar on the articles page, I gave it a value of — yeah, you guessed it — ‘articles’.

Then, create a file named ‘search.php’, and paste the following into it:

/* Template Name: Search Results */
$search_refer = $_GET["site_section"];
if ($search_refer == 'blog') { load_template(TEMPLATEPATH . '/blog-index.php'); }
elseif ($search_refer == 'articles') { load_template(TEMPLATEPATH . '/articles-index.php'); };

The important part here is, again, the third line. This looks up the value of the hidden input on the search form, and assigns it to the variable, ‘$search_refer’.

After that, the if statement decides, depending on the value of ‘$search_refer’, which template to load. The load_template function will ensure that the referenced page is shown, displaying the results from the search term.

One last thing you’ll need to do is edit the Post index. In this example, I’ll show you what was added to‘blog-index.php’. This goes directly before The Loop.

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts("s=$s&amp;paged=$paged&amp;cat=4");
endif;

For now, I’m going to admit ignorance about the second line (and if you can explain it, then please, go ahead!). I don’t fully understand what purpose it serves — I pieced this solution together from a few places — but the third line (what’s with that?!) has the important bit you need to pay attention to.

On this client’s site, the ‘Blog’ Category has an ID number of ’4′; that’s why the ‘query_posts’ function has‘cat=4′ at the end — this only includes Posts from that Category in the output.

On the ‘articles-index.php’ template page, ‘query_posts’ has ‘cat=3′, to only show ‘Articles’ Posts. Fairly straightforward, right?

In this particular example (and I thought it best to show it as closely to my working version as is clear), I’ve sent the different results to different template pages because those templates differ to a large degree. However, if your search results templates for the different sections are identical (or nearly), then you could skip out the ‘search.php’ file, and this to your index file:

if( is_search() ) :
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ($search_refer == 'blog') { query_posts("s=$s&amp;paged=$paged&amp;cat=4"); }
elseif ($search_refer == 'articles') { query_posts("s=$s&amp;paged=$paged&amp;cat=3"); };
endif;

That should do the whole lot after the search form in one step! If you’ve come up with a more elegant solution to this, or know a more efficient way to implement this solution, then please leave a comment — we all benefit from sharing tips like these!

How to detect Browser in PHP

Detecting the user’s browser type and version is helpful in web applications that harness some of the newer bleeding edge concepts. With the browser type and version you can notify users about challenges they may experience and suggest they upgrade before using such application. Not a great idea on a large scale public site; but on a private application this type of check can be helpful.

In an active project of mine we have a pretty graphically intensive and visually appealing user interface which leverages a lot of transparent PNG files. Because we all know how great IE6 supports PNG files it was necessary for us to tell our users the lack of power their browser has in a kind way.

Searching for a way to do this at the PHP layer and not at the client layer was more of a challenge than I would have guessed; the only script available was written by Gary White and Gary no longer maintains this script because of reliability. I do agree 100% with Gary about the readability; however, there are realistic reasons to desire the user’s browser and browser version and if your visitor is not echoing a false user agent we can take an educated guess.

I based this solution off of Gary White’s original solution but added a few things:

  • I added the ability to view the return values as class constants to increase the readability
  • Updated the version detection for Amaya
  • Updated the version detection for Firefox
  • Updated the version detection for Lynx
  • Updated the version detection for WebTV
  • Updated the version detection for NetPositive
  • Updated the version detection for IE
  • Updated the version detection for OmniWeb
  • Updated the version detection for iCab
  • Updated the version detection for Safari
  • Added detection for Chrome
  • Added detection for iPhone
  • Added detection for robots
  • Added detection for mobile devices
  • Added detection for BlackBerry
  • Added detection for iPhone
  • Added detection for iPad
  • Added detection for Android
  • Removed Netscape checks
  • Updated Safari to remove mobile devices (iPhone)

Read the rest of this entry

Control a YouTube RSS feed with PHP

This was the result of a fair bit of Googling and reworking – the original posts were Netweblogic, MikeBris, and Olate.

It’s based on the MagpieRSS parser, which takes an RSS feed and formats it. However, I had some problems in getting the code in the NetWebLogic post to work, plus since it was written, I think some of the YouTube code has changed, and the world has moved on to want validating code that doesn’t use <embed>.

I finally assembled three pages – one which displays all of a YouTube RSS feed, one which displays a specified number of RSS feeds – these were both master lists, and then a detail page from either which shows the actual movie.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
// get the feed using magpieRSS
    require_once('rss_fetch.inc');
	$rss = fetch_rss("http://gdata.youtube.com/feeds/api/users/[CHANNELNAME]/uploads?alt=rss");
 
?>
<?php
if(count($rss->items)>0){
	foreach ($rss->items as $video){ //Get all of the feed
		//Get the video ID
			preg_match("/http:\/\/gdata.youtube.com\/feeds\/api\/videos\/(([a-zA-Z0-9]|-|_)*)/", $video['guid'], $videoIdMatches);
			$videoID = $videoIdMatches[1];
		?>
<div class="video">
  <h3>
    <?php echo ucfirst($video["title"]) ?>
  </h3>
  <a href="youtube_embeddedvideo.php?url=<?= $videoID ?>"><img src="http://img.youtube.com/vi/<?php echo $videoID ?>/0.jpg" alt="<?php echo $video["title"] ?>" width="100" class="left_image" /></a>
  <p><strong>Date :</strong>
    <?php echo date("d M Y", strtotime($video['pubdate']) ) ?>
  </p>
  <p>
    <?php echo $video->description ?>
  </p>
  <div style="clear:both"> <a href="youtube_embeddedvideo.php?url=<?php echo $videoID ?>">Watch it here</a><br />
    <a href="http://uk.youtube.com/watch?v=<?php echo $videoID ?>">Watch it on YouTube</a><br />
  </div>
  <br />
</div>
<?php
	}
}else{
	echo "<h3>No Videos Found</h3>";
}
?>
</body>
</html>

Useful Syntaxes that Used in Smarty

Smarty is a template engine for PHP. More specifically, it facilitates a manageable way to separate application logic and content from its presentation. So today am going to simple  trick that useful in smarty development.

Here is way to assign Php variable to smarty variable:-

$this->assign('<<Name_of_smarty_variable>>',<<Name_of_php_variable>>);
{assign var="<<smarty_variable_name>>" value=<<smarty_variable_name_that_you need to assign>>}

Here is way to assign smarty variable to Php:-

$pro_id=$this->_tpl_vars['<<smarty_variable_name>>'];

How to give print_r in smarty:-

{<<Smarty_variable_name>>|print_r}

If you really interest in this just follow this reference. Click Here

Good Luck..

 

How to validate xml document.

This entry is part 2 of 2 in the series xml from the Beginning

As I mentioned on my early post we need to care about validation of xml document.  E can validate xml document by using two ways.

  • DTD – Document Type Definition.
  • Xml schema.

So today am going to discuss how to validate using DTD. Actually we can use DTD in two ways.

  • External DTD.
  • Internal DTD.

External DTD:-

We can include external DTD document same as javascript.  We can include external DTD document in to our xml document by following way.

<!DOCTYPE <<root element>> SYSTEM <<file name>>>

 

You have to replace <<root element>> with name of root element and <<file name>> with name of file with data type. Now let’s see how to implement DTD document. Before add rules you have to implement DTD by using following code.

<!DOCTYPE note
[
----validation rules----
]>
 

Then we have to declare all elements in xml document under root element. We can do that in following way.

<!ELEMENT <<root element>> (<<child elements>>)>
 

Same as above we done you need to replace <<root element>> with name of root element and <<child elements>> with names of child element separated by commas. Then you need to add rules for validation. You can add rules in following way.

<!ELEMENT <<element name>>(<<data type>>)>
 

You have to replace <<element name>> with name of element and <<data type>> with valid datatype that you need.

So our DTD document is finished now! You can check validity of your xml document by using any xml validator. I already uploaded demo file for your better understand. You can download it by clicking on here. We have another method to validate xml document. So I will explain how to validate xml document using xml schema.

Good Luck.

 

 

<!DOCTYPE note

[

----validation rules----

]>

 

You have to replace <<root element>> with name of root element and <<file name>> with name of file with data type. Now let’s see how to implement DTD document. Before add rules you have to implement DTD by using following code.

If you follow my old post hope now you can implement your own custom theme. So today I hope to explain how to develop our theme according to standard. WordPress organization gives standards for wordpress theme. If you develop wordpress themes for commercial purposes it is important to it should be develop according to standards. When talking about this standards we can divide this in to two sections. They are,

  1. WordPress Coding Standards
  2. CSS Coding Standards.

WordPress Coding Standards:-

In this topic am going to explain the standards for theme source code.  I will explain them point by point,

  • Use single and double quotes when appropriate.

If you’re not evaluating anything in the string, use single quotes. You should almost never have to escape quotes in a string, because you can just alternate your quoting style.

  • Your indentation should always reflect logical structure.

Use real tabs and not spaces, as this allows the most flexibility across clients.

  • Don’t use php tags in short form (ex:- <?—–?>).
  • Make sure you remove trailing whitespace after closing PHP tags.
  • Remove trailing spaces at the end of each line of code.

I recommend you to use any online formatting tool to format source code.

Ex :- Click here to use Php Formatter.

  • Formatting SQL statements.

When formatting SQL statements you may break it into several lines and indent if it is

sufficiently complex to warrant it. Most statements work well as one line though. Always capitalize the SQL parts of the statement like UPDATE or WHERE.

  • Avoid touching the database directly.

If there is a defined function that can get the data you need, use it. Database abstraction

(using functions instead of queries) helps keep your code forward-compatible and, in cases where results are cached in memory, it can be many times faster.

  • In general, readability is more important than cleverness or brevity.
  • Use lowercase letters in variable and function names (never camelCase). Separate words via underscores.
  • If you don’t use a variable more than once, don’t create it. This includes queries. Always use the wpdb class of functions when interacting with the database.
  • When doing logical comparisons, always put the variable on the right side.
  • And also don’t forget to check validity of your HTML by using HTML Validator. Click here to use the W3C validator.

So still we have to talk about CSS Coding Standards. I will explain it on my next post.

Good Luck!!

© Copyright 2011 - Dilina Nilakshana