Tutorial: How to get image path on a post in WordPress efficiently

This is something that WordPress currently doesn't support yet. You will face the problem of retrieving image on a particular post on the loop while you are working on WordPress theme or plugin. WordPress doesn't provides you with a method that you can use to retrieve the images on the post and you would have to search all over the internet to find someone sharing their secret with you. Thus, rather than using a complex or methods built by others, i personally have a much simple and efficient way of doing this.

The Problem

I wanted to retrieve all images on a particular post under a category and make it into a gallery. However, WordPress doesn't provides such method. Furthermore, the methods provide by others seems to complex this particular function. I want a simple and efficient way of doing this. Not a redundant one.

The Solution

The best way is to look into the core of PHP and search for a particular function that do this automatically. I search quite long and finally found preg_match_all from PHP core build. However, it return the number of match element instead of the result of the URL! But if you read closely it can also retrieve the matched result. So, how do you retrieve the images? Answer is regular expression! What i did was as follow,

$content = get_the_content();
preg_match_all('/src=\"https?:\/\/[\S\w]+\"/i', $content, $matches, PREG_SET_ORDER);
foreach($matches as $e)
{
	echo '<div class="slideshow_box"><img width="106px" '.$e[0].'/></div>';
}

Basically, i retrieve the content using WordPress method 'get_the_content()'. Using the preg_match_all PHP function i placed a regular expression that will retrieve all string that start with 'src="' and end with a single '"' quote symbol. You can read more on regular expression on Google (although until now i still can't find a real good reference). it will return the number of match result normally but with the additional variable, $matches which store all matched string, we can easily get all images on a post in WordPress without building additional big function to do this. You can remove 'src=' to retrieve something like 'www.hungred.com' instead of 'src="www.hungred.com' but if you know regular expression better than i do, this will easily be a piece of cake for you.

The Conclusion

This may seems to be an obvious thing to do. But you may be surprise after doing some Google search that many people actually built up function just to accomplished this and no one is sharing such sweet method with you! This is just to write out to help others who are still searching for a better solution than looking at complex method created by others. Hope it help.

Tutorial: Simple grey out screen effect with jQuery

Grey out screen is done previous in JavaScript. But jQuery has became so powerful in reducing the number of codes required that makes me wanted to try how well this can be done using it. Personally, i wanted to check out how easy it is to create a grey out screen with a pop out box at the center of the screen. This is purely for the sake of exploring and experiencing how simple can a grey out screen be done in jQuery.

The Objective

The objective of this article is to produce a simple grey out screen effect in jQuery with the minimum amount of code required. Of course, this is just the goal. But let's see how simple and easy this can be done with minimum amount of codes and maximum completeness.

The Requirement

Here are the following requirement for this simple tutorial

  • Basic CSS, HTML, jQuery Knowledge
  • Read what is written!

Although it is obvious, but usually people tend to skip the second requirement.

The Concept

Let's imagine the body tag (also known as <body>) is the curtain and the box is the person who will appear when the curtain is closed. If the box is in the body when the curtain is closed, we won't be able to see the box!(you will see no person out on the front when the curtain closed). Furthermore, if we grey out the body tag the background of the page will change to black instead of grey which is not what we want. Therefore, the grey out screen should be placed as a standalone curtain just below the body tag (children of <body>). Normally, we will usually assume when the screen is grey out, all the child within the screen will also be grey out and those that are outside are unaffected. Unfortunately, this is not the case. It may surprise you but any element in the screen will be display instead! eg. anchor or hyperlink. Thus, if you want your element to be untouchable after grey out effect, it is best to placed grey out screen as standalone!

The Code

The code will be split into three part, HTML, CSS and jQuery. There will be more explanation than codes since we will want to understand what is going on in the code and the code is suppose to be MINIMUM

HTML

We will need three things in this article. They are 'box', 'screen' and 'button'.

	<input type='button' value='grey out me!' id='button'/>
	
	<div id='box'>
	</div>
	
	<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
	
	<div id='screen'>
	</div>

And finally a lot of break to make the page long enough to detect a problem later on. The elements are describe below,

  • box: the pop out box after screen grey out
  • button: the button that will initialize screen grey out
  • screen: the screen that will cover the whole page grey!

CSS

Well, on the CSS part we will style the 'box' and 'screen' only!

#box
{
	width: 150px;
	height: 150px;
	background: #FFF;
	border: red dotted 5px;
	text-align: center;
	position: absolute;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
	z-index: 20;
	display: none;
}

#screen
{
	position: absolute;
	left: 0;
	top: 0;
	background: #000;
}

These can be placed in jQuery code instead but since we want it to render faster, placing them in CSS will be a much better option(It really depend on you). Let me explain the 'box' CSS first.

  1. Give 'box' a width, height, background color and border so that it is visible on the screen
  2. align 'box' to center
  3. position it as absolute and make it visible(z-index) even when the screen is grey out
  4. margin-left/top,top,left are to align it on the center of the screen (cross browser) but in a fixed way
  5. we hide it (the display)

The 'screen' CSS is fairly easy to understand. We have to position it as absolute and align it at the top left hand corner so that it will cover the entire screen!

jQuery

Above section should be quite clear and simple. But, the jQuery code is even easier to understand.

$(function(){
var pop = function(){
	$('#screen').css({ opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	$('body').css({'overflow':'hidden'});
	$('#box').css({'display': 'block'});
}
$('#button').click(pop);
});

The above should be quite basic. But the explanation are listed below,

  1. 'var pop = function(){..' wait until jQuery is ready!
  2. 'var pop = function(){..' create a function name 'pop'
  3. '$('#button').click(pop);..' attach an event handler, click onto the button
  4. '$('#screen').css({ opacity: 0.7, "w....' function activate we grey out the screen by providing the 'html' or 'page' width and height (instead of box size). This will cover the whole screen.
  5. '$('body').css({"overflow":"hidden"});' this is to fix the problem of using a 'fixed' center align CSS declaration
  6. '$('#box').css({"display": "block"});' this is to make the box appear!

It is really that easy! But going into grey out mode is simple, how about returning back to normal? Definitely, an extra event handler is required on the 'box' to reverse back the procedure!

$(function(){
var pop = function(){
	$('#screen').css({'display': 'block', opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	$('body').css({'overflow':'hidden'});
	$('#box').css({'display': 'block'}).click(function(){$(this).css('display', 'none');$('#screen').css('display', 'none')});
}
$('#button').click(pop);
});

I have just added two things above, can you identify them?

The Demo

The above demo and files can be viewed from the following link.

Wait!

I'm not done (nagging)! If you notice, i made a cheat on top to simplify the overall complexity. And the cheat is 'overflow: hidden' on the jQuery code. But not all browser support this! How about those that doesn't?! This is where i add in additional component so that we do not have to even rely on 'overflow:hidden'!

The Problem And Solution

The problem with the above grey out screen effect was due to the 'box' (the cheat was for 'box' too). remained at the same position when we are scrolling which is a big NO NO. Therefore, we can either make the box to align fixed at the center or move along while the user scroll (persistence box). We have illustrated the cheat for screen grey out effect using jQuery. Now we will do the second one, the persistence box.

The Persistence Box

The answer to persistence box is located at Align center of the screen while scrolling with css What we have to do here is to change the CSS 'box' position: absolute to position: fixed. Of course, we will have to remove the overflow: hidden on the jQuery statement. This will make it chase after your scroller and urge your users to take action on the 'box'. The final CSS code will look like this,

#box
{
	width: 150px;
	height: 150px;
	background: #FFF;
	border: red dotted 5px;
	text-align: center;
	position: fixed;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
	z-index: 20;
	display: none;
}

And we will remove overflow: hidden in jQuery and the final code will look like this,

$(function(){
var pop = function(){
	$('#screen').css({ opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	$('#box').css({'display': 'block'});
}
$('#button').click(pop);
});

This look even shorter than the previous one! Finally, we get a complete screen grey out effect in it simplest form.

Update 25 September 2009****
Matt asked a very good question below, this method will caused the grey out box stuck due to the css being set to 'fixed'. Hence, minimize to maximum in window browser will caused the grey out to stuck at the minimize size. Here is one of the solution you can live with.

$(function(){
var pop = function(){
	$('#screen').css({	"display": "block", opacity: 0.7, "width":$(document).width(),"height":$(document).height()});
	$('#box').css({"display": "block"}).click(function(){$(this).css("display", "none");$('#screen').css("display", "none")});
}
$('#button').click(pop);
$(window).resize(function(){
	$('#box').css("display") == 'block'?pop.call($('#button')):"";
});
});

I added an event handler during resize, check whether the box is displayed and it was displaying during resize we overwrite the pop out box again. The demo page was also updated for this update.

Demo for persistence box

The demo can be viewed on the following link!

Tutorial: How to vertical align center on the screen while scrolling with CSS

I believe some of you out there also faced this problem where your container is align on the center of the screen but when the screen is too long, the scroll bar appeared and your box remained on the top of the screen and you say "oh shit!". Searching all over the internet and found only how container can be align on the center of the screen but not when it was scrolling? I think this article will solve your problem.

The Problem

We are assuming here that you have aligned your container at the center of the screen with position absolute. If you are still having this problem, you may want to visit How to align center on the screen when using position absolute with CSS. Once your container has aligned on the center of the screen. You meet the problem of having it follow you while you scroll down the screen. I like to say that the container is not persistence enough! Let's make it persistence to follow your scroller.

The Concept

Basically, you can solve your container not aligned on center while scrolling with the following concept:

  • You can create a code of jQuery/JavaScript to accomplish this by making your container chasing after your scroller. Thus, changing the container position on every scroller movement. (not good)
  • The other way is to just CSS (which we are doing) to cheat the above effect. Instead of chasing after the scroller, we fixed the position on the center of the screen while having absolute to cover all other elements!

We will be doing the second approach which is more efficient and is the more correct way of doing. The reason why it must be position fixed is that the container should not move! Thus, stay at the center of the screen when you scroll. As for the reason why it must also be position as absolute is because we need to cover up all element below to prevent any user from clicking on the elements!

The Solution

The Trick is fairly simple after you have accomplished your center alignment on the screen with absolute position. I take the following code from the article and change it so that the container will remain center while scrolling.

#box
{
	width: 150px;
	height: 150px;
	background: red;
	padding: 5px;
	border: #CCC solid 1px;
	text-align: center;
	position: fixed;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
	
}

The above is the one was in the article given in the link. Now i will just change the styling a bit to red and size accordingly and the new code that will make it remain center will be as follow,

#box
{
	width: 150px;
	height: 150px;
	background: #000;
	padding: 5px;
	border: #CCC solid 5px;
	text-align: center;
	position: fixed;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
}

The main changes done was 'position:fixed' which fixed your container at the center of the screen whenever it go! Persistence enough.

The Demo

The following links are the demo for persistence and non-persistence container:

Tutorial: How to make your own simple and nice Slider with jQuery

Well, this is not new and can be easily found on jQuery UI but you will have to download jQuery UI and use it as if it is a plugin. But for my case, i wanted to find out and construct an easy and nice slider for myself. Many will skip this step and use jQuery UI instead. But when it come to customization for vertical slider, it may come to a good use for developers or even designers to know how this is being made (you can look into the code of a plugin but it will definitely take more time).

The Problem

I am currently building a gallery similar to the current Slider Gallery plugin. But i wish to know how slider can be achieve easily without using the existing plugin or library (learning purpose). The gallery can have vertical or horizontal slider and customize the outlook to my personal need.

The Solution

I can use the existing jQuery plugin or study them to construct a jQuery slider easily. But plugin codes contain many DOM manipulation to construct HTML structure automatic in order to ease the job needed for developers or designers. In return, we eliminated the efficiency of the website because of the extra codes required in the plugin to do things automatically. Personally, i will prefer something simple and easy to understand for future enhancement and maintenance by myself (i believe majority developers or designers will love simple stuff to work with). Thus, i brainstorm something similar to a slider which might not have the same concept as jQuery UI (i never actually look at it) but should be around the same.

The Concept

Before we go into the actual coding, i like to write a small concept out for myself to understand this in the future. Basically, we need two things in a slider, the scroller and scroll bar. But this two things are not enough. There is a need for an outer container to place these two. Why? Because we need to align both scroll and scroll bar together. Therefore, both the scroller and scroll bar will have to be position in absolute. The most outer container will be position relative to prevent the absolute positioned containers from getting out of the constraint area. So we will have something as shown below,
illustrate
In order to move it accordingly, we will move the variable 'left' since the scroller is positioned absolute and use variable 'top' if we are moving vertically.

The Code

The code will be split to three part, HTML, CSS and jQuery. This is best to simplify the overall concept.

HTML

The HTML code is fairly simple and straight forward. We will create the three container which were mention on the concept section as shown below,

	<div id="scrollcontainer">
		<div id="scrollbar">
		</div>
		<div id="scroller">
		</div>
	</div>

i have placed the id for each container so that we can manipulate them when we come to jQuery coding. Short and clear.

CSS

In the CSS, this play a much bigger role as most of the display is done in here. For the outer container we will just need it to be set to display:relative, provide a width and align to center. For scroller and scroll bar will required more declaration.

#scrollcontainer
{
	margin: 0 auto;
	text-align: center;
	position: relative;
	width: 907px;
}
#scrollbar
{
	width: 907px;
	height: 40px;
	position: absolute;
	top: 0;
	left: 0;
	background: transparent url('../images/scrollbar.png')  no-repeat;
}
#scroller
{
	background: transparent url('../images/scroller.png') no-repeat;
	width: 196px;
	height: 40px;
	position: absolute;
	left: 0px;
	top: 0px;
}

Basically i set my scroll bar width and height so that the image can be placed into it. Finally, the container with the scroll bar image is set to position absolute with the top and left set to '0' in order for all browser to align properly ( or else you will see IE having problem). Similarly, the scroller part was also being done in this way. Simple enough.

jQuery

As usual, this is the most complex part which you should focus more. We will need to define some variable before we attached any event handler and other operation.

	var myoffset = $('#scroller').offset();
	var myxpos = parseInt(myoffset.left); 
	var width = parseInt($('#scrollbar').css("width")) - 196;
	var action = false;

We will need to declare the above variable so that we can easily maintain them when required without manipulate the inside logic of the slider. The variables are explain below,

  • myoffset: this is the offset position of the 'scroller' container. Similarly, this object return contains 'scroller' position
  • myxpos: using 'myoffset' object, we retrieve the 'x-axis' position
  • width: this is the actual width of the scroll bar (we substract 196 because the scroller width is 196px)
  • action: this is to indicate whether the scroller was clicked and holded

Now we will have to grab the coordinate of the mouse position and attach the event handler required for the slider to work.

	$().mousemove(function(e){
		
	})

The above will gives us the position of our mouse coordinate. Now will will look at the overall code within mousemove declaration.

	$().mousemove(function(e){
		var move = parseInt(e.pageX-myxpos);
		
		$('#scroller').mousedown(function(){
			action = true;
		})
		$('*').mouseup(function(){
			action = false;
		});
		
		if(move <= 0)
			move =0;
		if(move >= width)
			move = width;
		if(action)
		$('#scroller').css("left", (move)+"px");
				
	})

The 'move' variable gives us the real mouse position. Since the most left of the screen will gives us '0px' but it is not necessary that the scrollbar will always be at the most left of the screen. It can be at the center of the screen where the position of its starting point is also '0px'. Thus, we will need to subtract away the distance between the scroll bar containers and most left of the screen. Short to say, our mouse X coordinate will always be bigger than our scroll bar X coordinate. So we will have to make it similar by doing some subtraction.

The 'move' variable is troublesome explanation, let's move on. We attached two event handler to mousedown and mouseup to detect whether the user clicked on the 'scroller'.

Finally, we will detect whether the 'real mouse position' has moved over the constrained area and set the 'real mouse position' to the minimum or maximum of the area (indicate black on the concept section image). This is required so that it can move smoothly when it reaches the end of the scroll bar. We also use the variable 'action' to detect whether the 'scroller' was clicked before it is able to move.

The overall jQuery code for a slider to work is as follow,

$(function(){
	var myoffset = $('#scroller').offset();
	var myxpos = parseInt(myoffset.left); 
	var width = parseInt($('#scrollbar').css("width")) - 196;
	var action = false;
	
	$().mousemove(function(e){
		var move = parseInt(e.pageX-myxpos);
		
		$('#scroller').mousedown(function(){
			action = true;
		})
		$('body').mouseup(function(){
			action = false;
		});
		
		if(move <= 0)
			move =0;
		if(move >= width)
			move = width;
		if(action)
		$('#scroller').css("left", (move)+"px");	
	})
});

P.S: This is just a simple version on how slider can be done. It can definitely be improved! But this is just to illustrate a Silder for your understanding.

P.S: The full version without using jQuery Plugin or UI can be found at Tutorial: How to make your own simple and nice Slider with jQuery part 2

The Demo

The explanation might not work for you let's look at the demo i prepared which locate at jQuery slider demo, the image can be seen below,
jquery-slider-demo
Unfortunately, i did not make the container dynamic (means you can move them around) to test the important of the 'move' variable as describe above. Nonetheless, you can always download the demo down to your local PC at jQuery Slider demo files and modify the CSS position to test the slider! Hope you learn something too!

Tutorial: How to create an image navigation bar with CSS

There are times when we want to build a navigation bar for ourselves in the simplest form. Especially when we want an image on top of an image or below an image but perform it with many many redundancy codes made in HTML, CSS or even involved JavaScript. What i am going to demonstrate here is a simple yet powerful method we can all use in CSS to create such navigation bar that attached an image on top of it.

The Problem

I wanted to create a navigation bar that will display an image when hover on it and display when it is not being hovered.

The Concept

The solution to this problem is fairly simple but usually over complicated. We want an image and a word to be placed together in the same row and column on the navigation bar. Some people will do this with the following methods:

  • Create a two row of div block align them perfectly top to be image, bottom to be word
  • Use jQuery or JavaScript to assist with the effect and display of the image
  • Use position absolute to align it on top of the image
  • The list goes on..

To be honest, what we really need is just an unordered list with some CSS. What we do is to stretch the list box so that it can contain an image and place a anchor as the child of the list. This way, the image can be display on the list box as background while the word will always be display as it is. Simple and sweet.

Solution

I will split this into two section as this is all we need to accomplish this effect, HTML and CSS.

HTML

			<ul id="content-nav">
				<li class="boxes" id="0"><a href="#">HOME</a></li>
				<li class="boxes" id="1"><a href="#">ROCK</a></li>
				<li class="boxes" id="2"><a href="#">BAD</a></li>
				<li class="boxes" id="3"><a href="#">TIME</a></li>
			</ul>

Assume we have an unordered list as shown above in HTML. Now we will use CSS to demonstrate how it can be done.

CSS

#content-nav
{	
	list-style: none; /*removes the underline below the link*/
	padding: 0; /*removes the padding*/
}
#content-nav li
{
	
	float: left; /*this makes the element displays in a horizontal line*/
	width: 50px; /*This allows the picture to be fit in the block*/
	height: 50px; /*This allows the picture to be fit in the block*/
	margin-left: 50px;
	cursor: pointer;
	
}
#content-nav li:hover
{
	background: transparent url(../images/1.png) no-repeat top center; /*this makes the picture appears in the top center without any repeats*/
}
#content-nav li a
{
	color: #777;
	display: block;  /*The element will be displayed as a block level element */
	width: 50px; /*This allows the picture to be fit in the block*/
	padding: 50px 0px 5px; /*There is 60px of padding on the top, 10px of padding on the right and left, and 5px of padding on the bottom*/
	text-decoration: none; /*removes all text decoration*/
}

What we do here is to remove all styling on the anchor so that it won't display any underline etc. Then, we set the anchor to display: block so that it will go to the next line after the image appeared. but we will have to provide a space for the image. Thus, padding is used instead. The description i am talking about is located at #content-nav li a. We set the background image when hover with this CSS declaration #content-nav li:hover. Others should be self explain stuff.

Demo

You can view the demo site at CSS image navigation bar with CSS. It will display the image when mouse hover. Cheers