How to move WP database to new domain without sql queries
Apr 26th
It happened that i needed to move a wordpress site from one domain to another, all simple, move the files, export the database, make a search and replace for the site’s url and replace it with the new url, then import the DB and all should be fine, …except that all the text widgets were missing. It seems like, the text widgets have serialized data stored in sql, so a blind find/replace messed up the data.
You could use a tool that handles serialized data to do a find/replace, but wordpress makes it easy, and you can add just to lines to the wp-config.php file and you’re done.
define('WP_HOME','http://new-domain-path');
define('WP_SITEURL','http://new-domain-path');
jQuery Cycle with carousel thumbs pager
Feb 28th
An interesting cycle gallery ( like here http://jquery.malsup.com/cycle/pager3.html ), but to use less space, make the thumbnails pager a carousel. ( see a demo here … note, that this is just to prove the concept, not much attention was given to styles ).
If you have “Prev / Next” controls on the cycle slideshow, then you will stumble upon an annoying situation: When you cycle through the slides with the cycle controls, and reach the last visible thumbnail in carousel, you will have to use the carousel controls to go to the current slide’s thumb; to avoid this i used the cycle’s ‘onPrevNextEvent’ callback to navigate through the carousel in the same time you cycle through the slides.
You will need:
1. jQuery
2. Cycle plugin
3. any jquery carousel you want ( i have used jCarousel lite )
Make the markup as you want, and adapt the jQuery code to it.
$('#slideshow').cycle({
fx: 'scrollHorz',
speed: 'fast',
timeout: 0,
prev: '#prev',
next: '#next',
nowrap: 1,
pager: '#slide-pager ul',
pagerAnchorBuilder: function(idx, slide) {
// return selector string for existing anchor
return '#slide-pager ul li:eq(' + idx + ') a';
},
onPrevNextEvent: function(dir, id, el) {
if (dir === true) {
if (id >= 3) { //replace '3' with your number of visible elements
$('#slide-pager_next').click();
}
}
else {
if (id >= 1) {
$('#slide-pager_prev').click();
}
}
}
});
$("#slide-pager").jCarouselLite({
btnNext: "#slide-pager_next",
btnPrev: "#slide-pager_prev",
circular: false,
visible: 3
});
See the demo here.
Add CSS selectors that repeats
Nov 11th
Have you ever need it a way to style the elements of a set ( lets say 5 ) individually, but the same rules to be applied to other set ( of 5 ) ?
For example:
<div>
<h4>first</h4>
<p>lorem ipsum ...</p>
<h4>second</h4>
<h4>third</h4>
<h4>forth</h4>
<div>lorem ipsum ...</div>
<h4>fifth</h4>
<!-- here end our first set -->
<h4>first</h4>
<h4>second</h4>
<h2>lorem ipsum ...</h2>
<h4>third</h4>
<span>lorem ipsum ...</span>
<h4>forth</h4>
<h4>fifth</h4>
<!-- here end our 2nd set -->
</div>
and we want that the first h4 in the first set have same styles as the first h4 in the second and so on, of course our h4′s are not grouped, but they are scattered between other elements, and other h4′s can be added in the future.
If we have a way to distinguish our elements from the other then we can make a short script with jQuery to add classes.
For a group of five css classes that will repeat after a number ( for this example we took, n = 5 ), this means that our h4′s from 1 to 5 will have same classes with the h4′s from 5 to 10, and so on; for this we will use something that in math is called ‘modulo’, basically gives us the remaining of the division of two numbers, and as we can get the index of our element we can see which position has in our set ( in this case of 5 ).
$('div h4').each(function(index) {
if(index%5 == 0){
$(this).addClass('first');
} else if(index%5 == 1){
$(this).addClass('second');
} else if(index%5 == 2){
$(this).addClass('third');
} else if(index%5 == 3){
$(this).addClass('forth');
} else if(index%5 == 4){
$(this).addClass('fifth');
}
});
the result would be:
<div>
<h4 class="first">first</h4>
<p>lorem ipsum ...</p>
<h4 class="second">second</h4>
<h4 class="third">third</h4>
<h4 class="forth">forth</h4>
<div>lorem ipsum ...</div>
<h4 class="fifth">fifth</h4>
<!-- here end our first set -->
<h4 class="first">first</h4>
<h4 class="second">second</h4>
<h2>lorem ipsum ...</h2>
<h4 class="third">third</h4>
<span>lorem ipsum ...</span>
<h4 class="forth">forth</h4>
<h4 class="fifth">fifth</h4>
<!-- here end our 2nd set -->
</div>
Math trick to impress your friends
Nov 2nd
This is cool to impress someone with your “paranormal” skills.
Put someone to choose a random number, preferably a large one ( 3 or 4 figures ), and he (or she) have to keep this number secret from you and do the following math with it:
xyz = he’s or she’s chosen number ( ex. 315 )
Step1: xyz * 3 ( multiply by 3, ex. 315 * 3 = 945 )
Step2: then take the result and add all it’s figures ( abcd => a+b+c+d , ex. 945 => 9 + 4 + 5 = 18 )
Step3: Repeat Step1 with the new number ( the sum of figures, ex. 18 * 3 = 54 )
Step4: Repeat Step2 ( ex. 5 + 4 = 9 )
…
Repeat steps 1 and 2 until you get a one figure number.
When the person or persons finished the above algorithm, you tell them the number they’ve got ( which with the algorithm above will be always 9 !), and the question that will appear will sure be “How did you know ?”, …
try it!
WordPress promoted posts
Oct 16th
Show a number of posts ( or pages ) links and thumbnails images, randomly picked from a certain set.
For this we will need the set of ‘promoted’ posts ( or pages ), and a function to get the posts thumbnails.
For get the posts thumbnails function i will not insist and just use this one here. The set of ‘promoted’ posts will be a simple array of ID’s.
Add this to the functions.php file
function getPromotedLinks() {
// the array with the ID's of the posts ( or pages ) to be shown as promoted
$promoted = array( x, xx, xxx, ... n ); //here put your posts or pages ID's
$rand_ids = array_rand( $promoted, 5 ); //replace '5' with an integer of how many promoted items to be shown at once
//what will be showed in frontend
echo '<ul class="promotedlinks">';
foreach ( $rand_ids as $i ) {
//get the post (or page) image
$postID = $promoted[$i];
$all_images =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $postID );
if($all_images) {
$arr_of_all_images = array_keys( $all_images );
// Get the first image attachment from post
$firstImage = $arr_of_all_images[0];
// Get the thumbnail url for the attachment
// If you want the full-size image instead of the thumbnail, use wp_get_attachment_url() instead of wp_get_attachment_thumb_url().
$thumb_url = wp_get_attachment_thumb_url( $firstImage );
// Build the <img> string
$First_thumb_image = '<img src="' . $thumb_url . '" width="100" height="100" alt="Thumbnail Image" title="Thumbnail Image" />';
}
echo '<li><a href="'. get_permalink( $promoted[$i] ) .'">';
echo $First_thumb_image;
echo '<span>'. get_the_title( $promoted[$i] ) .'</span></a></li>';
}
echo '</ul>';
}
this is all, … you get a list of 5 (or how many you like), random links with thumbnails, which you can call anywhere ( inside loop, outside loop-> sidebar etc ), by <?php getPromotedLinks(); ?>.
Style as you wish,… an example would be:
ul.promotedlinks { margin: 0; list-style-type: none; }
ul.promotedlinks li { width: 125px; float: left; padding: 0; border-left: 1px solid #DDDDEE; overflow: hidden; }
ul.promotedlinks li:first-child { border-left: none; }
ul.promotedlinks li a { display: block; height: 100%; padding: 6px; }
ul.promotedlinks li a:hover { text-decoration: none; background: #DDDDEE; }
ul.promotedlinks li a img, ul.promotedlinks li a span { display: block; }
WordPress – Show author meta on author archive
Oct 4th
A neat feature for wordpress blogs or custom sites is to show the author biography and other information on the ‘author archive’ page.
For this we could use the ‘the_author_meta()‘ or get_the_author_meta functions to get the meta information we need, but if we want to show the author info outside the loop, so that even if the user has no published posts, it will still be visible. In order to do this we will get an object with all the info we need.
$userInfo = get_user_by('slug', get_query_var('author_name'));
and this holds all the info we need, and we will get it like this:
echo $userInfo->display_name echo $userInfo->first_name echo $userInfo->last_name echo $userInfo->eme_phone echo $userInfo->user_email echo $userInfo->user_url echo nl2br($aid->description) //etc
the nl2br() php function is used to return the user description with <br /> which are striped out by wordpress.
And changing the first parameter of the get_user_by function, to one of the supported values $field = ‘id’, ‘slug’, ‘email’, or ‘login’ , you can use this object in all places you need.
WordPress shortcodes for attachments
Sep 13th
A nice cool way to organize the attachments from a post or page, and not having to deal with ugly html in the wysiwyg editor, is using shortcodes. Just add the code below into your theme functions.php.
// [attachments]
function attachmentUrl($atts) {
extract(shortcode_atts(array(
"src" => ''
), $atts));
/* $filename_match = preg_match("/([a-zA-Z0-9_\.\-]+\.[a-zA-Z]+)$/", $src, $filename); */
$filename_match = preg_match("/\/([^\/]*$)/", $src, $filename);
return '<div class="attachments"><h4>Attachments</h4><ul class="attachments_list attachment"><li><a href="'.$src.'" target="_blank">'.$filename[1].'</a></li></ul></div>';
}
add_shortcode("attachment", "attachmentUrl");
// Audio shortcode
function audioURL($atts) {
extract(shortcode_atts(array(
"src" => ''
), $atts));
return '<audio src="'.$src.'" type="audio/mp3" controls="controls"></audio>';
}
add_shortcode("audio", "audioURL");
// Video shortcode
function videoURL($atts) {
extract(shortcode_atts(array(
"src" => ''
), $atts));
return '<video controls="controls" preload="none"><source src="'.$src.'" type="video/mp4" /></video>';
}
add_shortcode("video", "videoURL");
// Customize the 'insert into Post' action
add_filter('media_send_to_editor', 'my_filter_iste', 20, 3);
function my_filter_iste($html, $id, $caption, $title, $align, $url, $size, $alt) {
$attachment = get_post($id); //fetching attachment by $id passed through
$src = wp_get_attachment_url( $id );
$videoext = '.mp4';
$audioext = '.mp3';
$mime_type = $attachment->post_mime_type; //getting the mime-type
if ((substr($mime_type, 0, 5) == 'video') || (substr_compare($src, $videoext, strlen($str)-strlen($videoext), strlen($videoext)) === 0)) { //checking mime-type
$html = '[video src="'.$src.'"]';
} elseif ((substr($mime_type, 0, 5) == 'audio') || (substr_compare($src, $audioext, strlen($str)-strlen($audioext), strlen($audioext)) === 0)) { //checking mime-type
$html = '[audio src="'.$src.'"]';
} else {
$html = '[attachment src="'.$src.'"]';
}
return $html; // return new $html
}
and the ‘insert into post’ action will insert a shortcode similar to [attachment src="URL_to_attachment"] , that returns in frontend the HTML that corresponds to the uploaded file mime type.
CSS3 for IE with PIE
Aug 10th
PIE stands for “Progressive Internet Explorer”, and is capable to add support for the most useful, cool CSS3 features, to the old and grumpy internet explorer (6, 7 and 8), and make your life easier.
Look and this page ( http://www.antimath.info/demos/csspie/ ) in internet explorer, … border-radius, box-shadow, background gradient, …good bye images and useless markup, hello PIE.
.element {
width: 250px;
height: 150px;
line-height: 150px;
font-style: italic;
text-align: center;
border: 1px solid #999;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
-webkit-box-shadow: #444 0 0 10px;
-moz-box-shadow: #444 0 0 10px;
box-shadow: #444 0 0 10px;
background: #CCC; /*non-CSS3 browsers will use this*/
background: -webkit-gradient(linear, 0 0, 0 100%, from(#BEE224) to(#E9F648)); /*old webkit*/
background: -webkit-linear-gradient(#BEE224, #E9F648); /*new webkit*/
background: -moz-linear-gradient(#BEE224, #E9F648); /*gecko*/
background: -ms-linear-gradient(#BEE224, #E9F648); /*IE10 preview*/
background: -o-linear-gradient(#BEE224, #E9F648); /*opera 11.10+*/
background: linear-gradient(#BEE224, #E9F648); /*future CSS3 browsers*/
-pie-background: linear-gradient(#BEE224, #E9F648); /*PIE*/
behavior: url(pathTo/PIE.htc);
}
CSS3 PIE supports:
- border-radius
- box-shadow
- border-image
- multiple background images
- linear-gradient as background image
See more on css3pie.com
WordPress registration form in a regular page
Aug 4th
WordPress provides a function to echo in front end a simple login form ( wp_login_form( $args ) ), but it doesn’t provide a simple way to embed the registration form ( the form displayed in /wp-login.php?action=register ) in a regular page or sidebar.
After some google-ing and trying a few plugins, i decided it is more flexible if i make one myself. In my research to do this I stumble upon this article here which is the base of what i will explain below.
Make your own WordPress registration form:
Step 1
Create a file called ‘registration_form.php’ in your theme in which paste the code below.
<div class="registration-form-wrapper">
<?php
/* the captcha result is stored in session */
session_start();
if( isset( $_POST['svalue'] ) ) {
if($_POST['svalue'] != $_SESSION['answer']) {
$matherror = "Wrong math!";
}
else {
$matherror = " ";
}
}
include('arithmetic_captcha.php');
if(defined('REGISTRATION_ERROR')){
foreach(unserialize(REGISTRATION_ERROR) as $error){
echo '<p class="error">'.$error.'</p';
}
} elseif(defined('REGISTERED_A_USER')){
echo '<p class="success">Successful registration, an email has been sent to '.REGISTERED_A_USER .'</p>';
}
echo '<p class="error">'. $matherror .'</p>';
?>
<form id="my-registration-form" method="post" action="<?php echo add_query_arg('do', 'register', get_permalink( $post->ID )); ?>">
<ul>
<li>
<label for="username">Username</label>
<input type="text" id="username" name="user" value=""/>
</li>
<li>
<label for="email">E-mail</label>
<input type="text" id="email" name="email" value="" />
</li>
<li>
What is the result <strong><?php echo $math;?></strong> ? <input type="text" name="svalue" value="" size="7" />
</li>
<li>
<input type="submit" value="Register" />
</li>
</ul>
</form>
</div>
This is basically the HTML of the form.
Step 2
Add the ‘register user’ function, which you will find below, to your theme’s ‘functions.php‘ file, ..this will register the user and validate the form.
add_action('template_redirect', 'register_a_user');
function register_a_user(){
if(isset($_GET['do']) && $_GET['do'] == 'register'):
$errors = array();
if(empty($_POST['user']) || empty($_POST['email'])) $errors[] = 'Please enter a user name and e-mail.';
$user_login = esc_attr($_POST['user']);
$user_email = esc_attr($_POST['email']);
$sanitized_user_login = sanitize_user($user_login);
$user_email = apply_filters('user_registration_email', $user_email);
if(!is_email($user_email)) $errors[] = 'Invalid e-mail.';
elseif(email_exists($user_email)) $errors[] = 'This email is already registered.';
if(empty($sanitized_user_login) || !validate_username($user_login)) $errors[] = 'Invalid user name.';
elseif(username_exists($sanitized_user_login)) $errors[] = 'User name already exists.';
if(empty($errors)):
$user_pass = wp_generate_password();
$user_id = wp_create_user($sanitized_user_login, $user_pass, $user_email);
if(!$user_id):
$errors[] = 'Registration failed';
else:
update_user_option($user_id, 'default_password_nag', true, true);
wp_new_user_notification($user_id, $user_pass);
endif;
endif;
if(!empty($errors)) define('REGISTRATION_ERROR', serialize($errors));
else define('REGISTERED_A_USER', $user_email);
endif;
}
Step 3
Create a file called ‘arithmetic_captcha.php‘ which will contain a simple random numbers generator, for a simple ‘math captcha’ to keep the spam away. This simple captcha can be used with other forms as well, …just use the code below and the check made at Step 1.
<?php
session_start();
$nr1 = mt_rand(1,10); //mt_rand($min, $max)
$nr2 = mt_rand(1,10);
if( $nr1 > $nr2 ) {
$math = "$nr1 - $nr2";
$_SESSION['answer'] = $nr1 - $nr2;
} else {
$math = "$nr1 + $nr2";
$_SESSION['answer'] = $nr1 + $nr2;
}
Step 4
Just include the ‘register_form.php’ file created at Step 1 in your page template in place you want the form to appear.
<?php include('register_form.php');?>
Or you can just download the files here (wp_registration_form.zip) and include them in your theme.
Simple confirm password or email validation
Jul 22nd
If you have a form with a ‘confirm password’ field or ‘confirm email’, and you don’t want to use a heavy validation plugin just for a simple confirmation like this, you can always use some simple ‘old school’ javascript and the onblur event, so when it (the field ) loses focus the validation function do it’s job.
<script type="text/javascript">
function confirmPass() {
var pass = document.getElementById("pass").value
var confPass = document.getElementById("c_pass").value
if(pass != confPass) {
alert('Wrong confirm password !');
}
}
</script>
<form id="form" action="" method="post">
<label for="pass">Password</label>
<input type="password" id="pass" class="text" name="your_pass" value=""/>
<label for="c_pass">Confirm Password</label>
<input type="password" id="c_pass" class="text" name="your_c_pass" value="" onblur="confirmPass()"/>
</form>
See a demo.
Open flowplayer in fancybox
Jul 7th
Flowplayer is a good choice when it comes to embedding videos into websites, …but what about flowplayer in fancybox ?
If you google a bit certainly you’ll find some ideas of how to play a video in flowplayer in fancybox, but by far the most simple one and the one that gives you the control on every option of every movie embedded, is to embed each of your videos in one different page (ex. lets say we have movie1.mp4 and movie2.mp4 then we should have /movie1.html and /movie2.html or if you have just one video then just one page ), and then set the ‘href’ of the link that is supposed to open that video to the URL of the video page, and now when you click on the link it will open the video page in an iframe in the modalbox. To easily understand this see the demo.
Take note of the snippet of code bellow when you set fancybox.
$("#video-link").fancybox({
'width' : 336,
'height' : 256,
'overlayShow' : false,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'iframe' //tweek the other, do not change this;
});
How to test an optocoupler
Jun 28th
An optocoupler or optoisolator, is a device that contains a light-emitting diode (LED) and a photosensor ( photodetector, such as a photoresistor, a photodiode, a phototransistor, …etc ). The purpose of an optocoupler is to transfer signals from one circuit to another yet keep them galvanically isolated.
Here I want to show you how to check if an optocoupler is working. So i chose one of the most commonly used optocouplers ( PC123 – 4 pins) for the demonstration, but you can use the same principle for all optocouplers ( note: check the device datasheet first ).
Using the diagram in the right identify the pins; first the anode and cathode of the LED ( in this case pins 1 and 2 ), and then using an ohmmeter set on the ‘X1 Ohm’ domain, measure between pins 1 and 2, and you should get one reading measuring one way and no reading the opposite way (just like you measure a diode). If you get a value either way or no value at all, then certainly is a problem with the LED, and you should find another optocoupler.
Step 2
If the LED is good then we should check the phototransistor, you could measure it with the ohmmeter just like the LED between pins 3 and 4 ( the emitter and collector ), and you should get a high resistance value both ways if the phototransistor is good, if you’ll get no reading at all, is probably because most phototransistors have such high resistance between emitter and collector that the ohmmeter can’t measure; if this is the case you could connect in series two meters thus increasing the measuring domain; …although i think most don’t have two meters so i recommend the ‘empirical’ method, presuming you have a variable DC regulated power supply.
Empirical method
Connect the ohmmeter ( X1K Ohm or X10K Ohm ) between emitter and collector ( 3 and 4 ) like this: red probe to collector and black probe to emitter. Now connect a resistor of a few hundred ohms ( ~300 ohms ) in series with the LED anode, after this turn on the power supply and start increasing the voltage from 0 to 2…3 volts, and you should be able to see on the ohmmeter how the output resistance decreases as the input voltage increases and viceversa.
Post type targeting
Jun 18th
If you need custom displaying for different registered post types, you can use this trick:
$post_type = get_post_type( $post );
if ( is_single() && $post_type == 'your-post-type' ){
//what to be shown on single 'your-post-type' "page";
} else {
//what to be shown on every else single post "page";
}
you can use the same method on archive pages, by replacing the is_single() with is_archive(). Like an universal method you can try using,
$post_type = get_post_type( $post );
if ($post_type == 'your-post-type' ){
} else {
}
with same results, but if you want to be sure use the first example.
A more elegant solution is to use WordPress is_singular() function, but there are reported cases in which this would not work, …but is good to have more options from which to choose.
Hover effect on the parent of an anchor tag
Jun 18th
It ever happened that you need to apply some CSS style to the parent of a link ( anchor tag <a href=”"></a> ), when the link is hovered ?
For example this HTML:
<div> <a href="#">Some Link</a> </div>
you want to apply some styles to the <div> ( some background color for example ), and you can achieve this by using some ugly css selectors, but sure you will stumble upon some cross-browser problems, so you better use some simple jQuery manipulation.
$('a').mouseover(function (){
$(this).parent().addClass('hover');
}).mouseout(function (){
$(this).parent().removeClass('hover');
});
and now you can use the .hover class to style the <div>.


