Apply custom or random images to the featured pages

⚠️ Code snippets might not be compatible with the latest version of your theme. Always use a child theme to customize your theme, and test your code on a staging website before migrating to production.

By default in the Customizr theme, the featured pages images use by priority :

  1. the page featured images
  2. if the featured image is not set, then it uses the first image (ordered by date) attached to this page. (in other words, the first images that has been inserted in the WYSIWYG editor).

This snippet describes how to take control over the images displayed in the home featured pages block of the theme.

customizr-featured-pages

 

 

Even if the final plugin function is very simple to use, this snippet uses quite advanced php coding techniques. Before diving into the code or simply pasting the code into your functions.php file, you might want to make sure you understand the following php and WordPress coding concepts :

PHP :

 

WordPress

 

How to use the snippet

The snippet is fired by a function named fp_random_images() which can take up to 4 optional arguments :

  • type (string) : ‘attachment’ or ‘placeholder’. Default : ‘placeholder’.
    • ‘attachement’ : list of images from your media library
    • ‘placeholder’ : images from http://lorempixel.com/
  • images source options (string or array). Default : array(). This parameter depends on the first one :
    • if ‘attachement’ is choosen, then you have to provide an array of image’s id from your media library
    • if ‘placeholder’ is choosen, then you can set an array of image categories among the following : ‘abstract’ , ‘animals’ , ‘business’ , ‘cats’, ‘city’, ‘food’, ‘nightlife’ , ‘fashion’, ‘people’, ‘nature’, ‘sports’, ‘technics’ , ‘transport’. Note: if no category is choosen, the plugin will display image taken from randomly choosen categories
  • color (boolean). Default : true. Displays the image in color if true, in grayscale if false. Note : this parameter works only with the placeholder type.
  • random( boolean). Default : true. Works with the attachement type only.

 

Examples of use

Example 1 : nature random placeholder images

Note : parameter #3 set to false will display the placeholder images in greyscale.

fp_random_images('placeholder', 'nature' , false );

Example 2 : attachments from your media library

Note that the parameter #4 (random) is set to false and will replace the featured pages images in the same order of the array.

fp_random_images('attachment', array(10, 12, 25), true, false );

 

Commented source code

 

function fp_random_images( $type = null , $user_src = array(), $color = true , $random_on = true) {
	$type = ( ! in_array( $type, array('attachment' , 'placeholder') ) || is_null($type) ) ? 'placeholder' : $type;
	$user_src = ( is_null($user_src) || ! $user_src ) ? false : $user_src;
	//defines a global var available in all function scopes for the user args
	global $user_args;
	//populates this global with the user parameters
	$user_args = compact("type" , "user_src", "color", "random_on");
	//defines the default args to fallback to if user did not specify anything
	$defaults = array(
		'type' 						=> 'placeholder',
		'user_src' 					=> false,
		'color' 					=> true,
		'random_on'					=> true
	);
	//merges user args with defaults
	$user_args = wp_parse_args( $user_args, $defaults );

	add_filter( 'fp_img_src' , "_{$user_args['type']}_random_images", 10, 3 );
}


function _placeholder_random_images( $original_img, $fp_single_id , $featured_page_id ) {//<= the function parameters can be used to target a specific featured page
	global $user_args;
	extract($user_args, EXTR_OVERWRITE);
	
	//uses the the lorempixel.com categories, more here : http://lorempixel.com/
	$user_src 		= (false != $user_src && ! is_array($user_src) ) ? array($user_src) : $user_src;
	$img_cats     	= ! $user_src ? array('abstract' , 'animals' , 'business' , 'cats', 'city', 'food', 'nightlife' , 'fashion', 'people', 'nature', 'sports', 'technics' , 'transport') : $user_src;
	
	//Generates a range array => There are 10 images per categories in http://lorempixel.com/
	$img_index		= range(1,10);
	
	//checks unicity recursively
	$src = _get_unique_random( $type = 'placeholder', $data = array($img_cats, $img_index) );

	return sprintf('<img src="%1$s" width="270" height="250"/>',
		$src
	);
}

function _attachment_random_images( $original_img, $fp_single_id , $featured_page_id ) { //<= the function parameters can be used to target a specific featured page
	global $user_args, $randoms;
	extract($user_args, EXTR_OVERWRITE);

	//are user_src set as array?
	if ( ! is_array($user_src) )
		return $original_img;

	//declares the image ids list from your wp media library. Returns original if not set.
	$img_ids = ! $user_src ? false : $user_src;
	if ( ! $img_ids || empty($img_ids) )
		return $original_img;

	//gets a random image and checks its unicity recursively
	$rand_id = _get_unique_random( $type = 'id', $data = $img_ids );

	if ( 'no_images_left' == $rand_id )
		return $original_img;

	//checks if tc-thumb size exists for attachment and return large if not
    $image            = wp_get_attachment_image_src( $rand_id, 'tc-thumb' );
    $fp_img_size      = ( false == $image[3] ) ? 'medium' : 'tc-thumb';
    $fp_img           = wp_get_attachment_image( $rand_id, 'tc-thumb' );

	return ! $fp_img ? $original_img : $fp_img;
}

function _get_unique_random( $type, $data ) {
	global $randoms, $user_args;
	$randoms = ( !is_array($randoms) || empty($randoms) ) ? array() : $randoms;
	extract($user_args, EXTR_OVERWRITE);

	//check if we almost reach the random try limit and random is disabled and return the original image
	if ( isset($randoms['try_number']) && (49 == $randoms['try_number']) && ! $random_on )
		return 'no_images_left';

	switch ($type) {
		case 'placeholder':
			list($img_cats, $img_index) = $data;
			$_to_return = sprintf('http://lorempixel.com%1$s/270/250/%2$s/%3$s',
				! $color ? '/g/' : '',
				$img_cats[array_rand($img_cats, 1)],
				$img_index[array_rand($img_index,1)]
			);
		break;
		
		case 'attachment':
			$_to_return	= $data[array_rand($data,1)];
		break;
	}

	//security to avoid infinite loop if ids are < fp number
	$randoms['try_number'] = ! isset($randoms['try_number']) ? 1 : $randoms['try_number'] + 1;
	$randoms[] = ( in_array($_to_return, $randoms) && ($randoms['try_number'] < 50) ) ? _get_unique_random( $type, $data ) : $_to_return;

	return end($randoms);
}

 

That’s it!

I hope you’ll enjoy this piece of code and I look forward to reading your comments and improvements!

Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “Apply custom or random images to the featured pages”