WordPress get posts by taxonomy terms

With get_posts() you can do a lot of things, like creating multiple posts loops, retrieve posts by all sorts of criteria, etc.

One of the interesting part comes when you want to create a posts loop with only the posts from certain taxonomy term/terms.

On the codex page of the get_posts function, we find an example, which tells us to rename the ‘category’ argument with our taxonomy name, and it’s value is one of taxonomy’s terms name; but they don’t say anything about multiple terms. Well, it seems like it works if you pass a comma separated string of terms, the question now is how you can get a comma separated string of terms, of the current post, in single-posttype.php.

The get_the_term_list() seems to be just perfect for the job. The problem with this is that it also returns html anchor tags with the terms link; this can be solved with the strip_tags() php function.

$terms = strip_tags( get_the_term_list( $post->ID, 'taxonomy-name', '', ',', '' ) );

$arg = array(
	'numberposts' => 4,
	'orderby' => 'rand',
	'post_type' => 'post-type-name',
	'taxonomy-name' => $terms,
	'post_status' => 'publish'
$related_posts = get_posts ( $arg );

This can be a nice way to get random related posts who share same taxonomy terms.

How to move WP database to new domain without sql queries

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.


WordPress promoted posts and/or pages

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

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 hasn’t published any 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($userInfo->description)

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

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) {
      "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) {
      "src" => ''
  ), $atts));
  return '<audio src="'.$src.'" type="audio/mp3" controls="controls"></audio>';
add_shortcode("audio", "audioURL");

// Video shortcode
function videoURL($atts) {
      "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.

WordPress registration form in a regular page

Note: This code is old, and it may not work with the latest versions of WordPress

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">
/* the captcha result is stored in session */

if( isset( $_POST['svalue'] ) ) {
	if($_POST['svalue'] != $_SESSION['answer']) {
		$matherror = "Wrong math!";
	else {
		$matherror = " ";


    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 )); ?>">
	    <label for="username">Username</label>
	    <input type="text" id="username" name="user" value=""/>
	    <label for="email">E-mail</label>
	    <input type="text" id="email" name="email" value="" />
	    What is the result <strong><?php echo $math;?></strong> ? &nbsp; <input type="text" name="svalue" value="" size="7" />
	    <input type="submit" value="Register" />

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.';

      $user_pass = wp_generate_password();
      $user_id = wp_create_user($sanitized_user_login, $user_pass, $user_email);

        $errors[] = 'Registration failed';
        update_user_option($user_id, 'default_password_nag', true, true);
        wp_new_user_notification($user_id, $user_pass);

    if(!empty($errors)) define('REGISTRATION_ERROR', serialize($errors));
    else define('REGISTERED_A_USER', $user_email);

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.


$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 ‘registration_form.php’ file created at Step 1 in your page template or wherever you want the form to appear.

<?php include('registration_form.php');?>

Or you can just download the files here (wp_registration_form.zip) and include them in your theme.

Post type targeting

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.

WordPress admin panels disappearing


I encountered an annoying problem in wordpress admin, suddenly my Pages panel disappeared, I didn’t find the problem, and I needed that panel, so I added it manually, but as soon as i did that, other panels start to disappear. I thought it was an wordpress upgrade problem ( just did an upgrade ), but doing a downgrade didn’t solve it, so I start deactivating plugins, ( i mention i used MagicFields and Gravity forms, and i had 6 magic fields wright panels ), and when i deactivated Gravity forms all was normal, then i googled a bit and found that this is because plugins that use ‘add_object_page‘ function ( Magic Fields use it and Gravity forms as well ) make the Pages panel disappear when are more than 11 panels in the wordpress upper admin panel ( the one with Posts and Pages ), and the only solution is to change the ‘add_object_page‘ function to ‘add_menu_page‘, so i changed it in gravity forms and the Pages panel appeared.

This is not recommended, because the plugins might be upgraded and you have to be careful, but this was the only workaround that worked for me.

WordPress the_date vs. the_time

Hi !

This article is a friendly reminder for those like me, who can’t remember which wordpress function is used when.

Like the article title says is about the_date and the_time , because I wanted to make a post date look something like this:displaying the date on two rows. Like any “partially educated” web developer I wanted to achieve this by using the_date function with different parameters, like this:

<div class="post-date">
	<div class="month"><?php the_date(M) ?></div>
	<div class="day"><?php the_date(d) ?></div>

and then I discovered that it doesn’t work like I wanted to; the problem is that the second instance of the_date doesn’t work, is returning nothing, therefor just the month, no day … no good.

Lucky for me, I didn’t overload my brain too much trying to understand why is not working, and I gave another try, this time with the_time function, and … voilà ! , worked like a charm.

<div class="post-date">
	<div class="month"><?php the_time(M) ?></div>
	<div class="day"><?php the_time(d) ?></div>

So keep in mind !