CodeHQ

Archive for April, 2018

|

Grab first image from post

Monday, April 16th, 2018

Function for grabbing image from post and using it instead of a featured image for example.

Add this to functions.php

// Get URL of first image in a post
function catch_that_image() {
	global $post, $posts;
		$first_img = '';
		ob_start();
		ob_end_clean();
		$matches[1][0] = '';
		if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
		  	$first_img = $matches[1][0];
		}

	// no image found display default image instead
	return $first_img;
}

And call in the theme with

<img src="<?php echo catch_that_image() ?>" onerror="this.style.display = 'none';"/> 

Tags: , , , , , ,
Posted in PHP, WordPress | No Comments »

Query posts by current post category

Monday, April 16th, 2018

Great for showing ‘related posts’ by current post category. The current post has an ID, the query grabs that ID, checks with categories are associated with that post, creates an array and passes these through to the query, also excluding this current post from the loop.

Output is posts from the same category/categories as the current post (active page).

<?php 
	$args = array(
		'posts_per_page' => 3,
		'post__not_in'   => array( get_the_ID() ),
		'no_found_rows'  => true, //Np pagination needed so query is quicker
		'post__not_in' 	 => array($post->ID)  //Excludes current post
	);
 
	$cats = wp_get_post_terms( get_the_ID(), 'category' ); 
	$cats_ids = array();  
	foreach( $cats as $wpex_related_cat ) {
		$cats_ids[] = $wpex_related_cat->term_id; 
	}
	if ( ! empty( $cats_ids ) ) {
		$args['category__in'] = $cats_ids;
	}
	$wpex_query = new wp_query( $args );
 
	foreach( $wpex_query->posts as $post ) : setup_postdata( $post ); ?>
 
	//CONTENT HERE i.e. post data and title
 
<?php endforeach; wp_reset_postdata();?>

Tags: , , ,
Posted in PHP, WordPress | No Comments »