WordPress Snippets


Nov

13

WordPress Custom Field Image to Featured Image

Posted by CodeMunkyX

Do you have a theme that uses custom fields to hold image URLS and wish you could automatically set these as the featured post image, to be more compatable with other themes if you ever decided to change.

Well today is your lucky day, I ran across the need to do this on one of my recent free themes. Below is the code:


	// First lets get the custom field , we are assuming its called "thumb"
	$thumb = get_post_meta($post->ID, 'thumb', true);

	// Check if a post thumbnail is already set, if so don't do anything.
	if( has_post_thumbnail( $post->ID ) ) {

	} else {

		if ( ! empty($thumb) ) {

			// Download file to temp location
			$tmp = download_url( $thumb );

			// Set variables for storage
			// fix file filename for query strings
			preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $thumb, $matches);
			$file_array['name'] = basename($matches[0]);
			$file_array['tmp_name'] = $tmp;

			// If error storing temporarily, unlink
			if ( is_wp_error( $tmp ) ) {
				@unlink($file_array['tmp_name']);
				$file_array['tmp_name'] = '';
			}

			// do the validation and storage stuff
			$id = media_handle_sideload( $file_array, $post->ID, NULL );
			// If error storing permanently, unlink
			if ( is_wp_error($id) ) {
				@unlink($file_array['tmp_name']);
				return $id;
			}

			// Set the featured image
			set_post_thumbnail( $post->ID, $id );

		}

	}

Nov

02

WordPress Display All Images Associated with Page

Posted by CodeMunkyX

This is a code snippet I use quite often to display custom galleries in my themes. Paste the following code within the loop of your page template.

echo '<ul id="Thumbnails">';

$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {

$image_attributes 	= wp_get_attachment_image_src( $attachment->ID ); // returns an array
$imgTitle	        = $attachment->post_title;
$imgCaption 		= $attachment->post_excerpt;
$imgDescription		= $attachment->post_content;

echo '<li><a href="' . $attachment->guid . '"><img '; 

if ( $attachment->post_name == $_GET['image'] ) { echo 'class="active"'; }

echo ' src="' . $attachment->guid . '" title="' . $imgCaption . '" alt="' . $imgTitle . ' - ' . $imgDescription . '"  /></a></li>' . "\n";

}
}

echo '</ul>' . "\n";
echo '<div style="clear: both;"></div>';

Nov

02

WordPress Style First Word of Widget Titles

Posted by CodeMunkyX

Similar to my last post about adding html to the first word of titles, this is the code to do the same with widget titles. Just copy the code below into your functions.php file.

// Adds <span></span> around the first word of Widget titles
function arixWP_widget_title($title) {
$title = preg_replace('/(^[A-z0-9_]+)\s/i', '<span>$1</span> ', $title);
return $title;
}
add_filter('widget_title', 'arixWP_widget_title');

Nov

02

WordPress: Add HTML tags to first word of title

Posted by CodeMunkyX

While working on a theme, I needed code to add span tags around the first word of my titles in order to style them differently. Below is the code to do it. Just copy it into your functions.php file.


		function arixWP_title()
		{

			global $post;

			$title = '<h2 class="title"><a href="' . get_permalink() . '" title="' . get_the_title() . '" rel="bookmark">' . get_the_title() . '</a></h2>';
			$title = preg_replace('/<a([^>]+)>([A-z0-9_]+)\s/i', '<a$1><span>$2</span> ', $title);

			echo $title;

		}	

Usage

Where ever you would like the title to show up paste the following code:


<?php arixWP_title(); ?>

Sep

19

WordPress Count Post Views Without Plugin

Posted by CodeMunkyX

Did you ever want to know how many times a particular post has been viewed? Well today is your lucky day. Just add the following snippets to your template files and watch the post views grow.

Usage

Add this to your functions.php

	// Display or Count how many times a post has been viewed.
	// id = the post id and action = display or count

		function arixWp_PostViews( $id, $action ) {

			$axCountMeta 	= 'ax_post_views'; // Your Custom field that stores the views
			$axCount 	= get_post_meta($id, $axCountMeta, true);

			if ( $axCount == '' ) {

				if ( $action == 'count' ) {
					$axCount = 0;
				}

				delete_post_meta( $id, $axCountMeta );
				add_post_meta( $id, $axCountMeta, 0 );

				if ( $action == 'display' ) {
					echo "0 Views";
				}		

			} else {

				if ( $action == 'count' ) {

					$axCount++;
					update_post_meta( $id, $axCountMeta, $axCount );

				} else {

					echo $axCount . ' Views';	

				}

			}	

		}

To count the views add this to your single.php template.

<?php echo arixWp_PostViews( get_the_ID(), 'count' ); ?>

To display the count outside the loop use this:

<?php echo arixWp_PostViews( get_the_ID(), 'display' ); ?>

If you want them to show in the loop use this instead.

<?php echo arixWp_PostViews( $post->ID, 'display' ); ?>

Sep

13

WordPress – Custom Taxonomy Breadcrumbs

Posted by CodeMunkyX

While developing a theme that uses custom taxonomies and custom post types, I ran across the need to include breadcrumb navigation to the custom taxonomies. After a couple of days of searching around and not finding any real solutions, I ended up creating my own function to do it.

Enjoy

Copy this to your functions.php file

<?php

	function postTypeCrumbs($postType, $postTax) {

		$term 			= get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
		$taxonomy 		= get_taxonomy($term->taxonomy);
		$parents 		= get_ancestors( $term->term_id, $postTax );
		$parents 		= array_reverse($parents);
		$archive_link	= get_post_type_archive_link( $postType );

		echo '<ul class="ax_crumbs">';

		if ($taxonomy)  {
			echo '<li><a href="' . $archive_link . '" title="' . $taxonomy->labels->name . '">' . $taxonomy->labels->name . '</a> &raquo; </li>';
		}

		foreach ( $parents as $parent ) {
			$p 	= get_term( $parent, $postTax );
			echo '<li><a href="' . get_term_link($p->slug, $postTax) . '" title="' . $p->name . '">' . $p->name . '</a> <span>&raquo;</span> </li>';
		}

		if ($term) {
			echo '<li>' . $term->name . '</li>';
		}

		echo '</ul>';

	}
?>

Usage

Paste this whereever you would like the taxonomy to display.

<?php postTypeCrumbs('post type', 'taxonomy name'); ?>

Aug

30

Include Custom Post Types in WordPress Feed

Posted by CodeMunkyX

We just implemented a new WordPress site that incorporated custom post types and noticed that our default feed was only showing the standard “post” type content. After searching around, we found the below code snippets. One thing to note, is be sure and update a post afterwards, because I did not see a change in the feed until doing so. Enjoy!

Includes All Post Types

<?php
function myfeed_request($qv) {
	if (isset($qv['feed']))
		$qv['post_type'] = get_post_types();
	return $qv;
}
add_filter('request', 'myfeed_request');
?>

Includes Post Types Specified

<?php
function myfeed_request($qv) {
	if (isset($qv['feed']) && !isset($qv['post_type']))
		$qv['post_type'] = array('post', 'story', 'books', 'movies');
	return $qv;
}
add_filter('request', 'myfeed_request');

?>

Aug

26

Shorten Post Content for Display in Theme

Posted by CodeMunkyX

We have all needed to shorten post content in WordPress for displaying in a particular theme or section of your website. Sure, you could use post excerpt field in WordPress, but this isn’t always applicable. One of the issues with parsing post content is it usually has markup code and/or shortcodes that haven’t been processed. So when you trim to a certain char / word length it counts these and you don’t get a true representation of data that you wanted. Below is a snippet of code that filters any tags and shortcodes and then returns you the desired amount of words from your post content.

Invoke Function

The first parameter in the limit_words function is the content you wish to extract the amount of words (second parameter) from.

    <?php echo limit_words(get_the_content(), '40'); ?>

Function Declaration

<?php
function limit_words($string, $word_limit)
{
    $string = strip_shortcodes($string);
    $string = strip_tags($string);

    $string = preg_replace("/&#?[a-z0-9]{2,8};/i","",$string);
    $words = explode(' ', $string);
    if (count($words) > $word_limit) {
	return implode(' ', array_slice($words, 0, $word_limit)) . " ...";
    } else {
	return implode(' ', array_slice($words, 0, $word_limit));
    }
}
?>

Aug

24

Set WordPress Post Excerpt Length

Posted by CodeMunkyX

Simple little WordPress snippet that sets the length of your WordPress post excerpt so it will fit more in-line with the theme you are currently using. Just set the value below (currently 30), and it will update it so that your excerpt is that many characters.

Place in functions.php

<?php
function excerptLength( $length )
{
	return 30;
}

add_filter( 'excerpt_length', 'excerptLength' );
?>

Aug

23

Remove WordPress Version

Posted by CodeMunkyX

A quick and simple WordPress snippet that removes the WordPress version from your blog’s header. Just paste the below into your functions.php file. The below utilizes the ‘the_generator‘ filter to invoke the user-defined function removeWPversion to return a blank instead of the WordPress version.

<?php
// Remove WordPress Version
function removeWPversion()
{
   return '';
}

add_filter('the_generator','removeWPversion');
?>

featured wordpress themes