This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

Get all image attachments from a single WordPress post or page

This is probably one of my personal favorite snippets always very useful for sliders and gallerys, perfect for portfolio items. With this little snippet you’ll get all images attachments from a single WordPress post or page.

<?php
$args = array(
	'order'          => 'ASC',
	'post_type'      => 'attachment',
	'post_parent'    => $post->ID,
	'post_mime_type' => 'image',
	'post_status'    => null,
	'numberposts'    => -1,
);
$attachments = get_posts($args);
if ($attachments) {
	foreach ($attachments as $attachment) {
		echo wp_get_attachment_image($attachment->ID, 'custom-image-add-image-size-function');
	}
}
?>

Don’t forget to change ‘custom-image-add-image-size-function’ to your own specific image size.

Source Codex but, I think DIGWP do a better job of explaining this simple snippet.

Close WordPress Comments on All Posts and Pages Temporarily

The following snippet will close commenting throughout the whole website (or network, if network-activated), but will retain the original comment status on all posts and pages, so you can reopen commenting at any time.

add_filter( 'comments_open', '__return_false' );

It might come useful in several cases, like when you’re experiencing a massive attack of comment spam, or perhaps your website is under heavy load, and comments are causing your page cache to get busted. Or maybe you’re just going for vacation and don’t want to end up with a pile of comments you have to respond to when you get back 😉

Add Custom Columns to WordPress Post Type Lists

The combination of custom post types and custom meta boxes is a powerful one for using WordPress as a content management system. But if key data about a post is stored in meta boxes it’s often helpful to see it in the list of posts.  For example, the “Countries” post type shown below benefits from some custom columns, including one that displays a little flag.

This snippet lets you modify, and add to the  columns for a given post type. The comments explain as we go. Be sure to edit the <prefix> and <post-type> to be your own.

// Add a filter to add extra columns for a specific post type's edit list
add_filter("manage_edit-<post-type>_columns", "<prefix>_<post-type>_edit_columns");

// Add an action to populate the custom columns
add_action("manage_<post-type>_posts_custom_column", "<prefix>_<post-type>_custom_columns");

// This function takes an array of columns and should return an array of columns.  It should add
// to the list of columns that's given as an input.  The array keys are column ID strings and the array
// values are column heading strings.
function <prefix>_<post-type>_edit_columns( $columns ) {
    // Add the extra custom columns
    $columns['logo'] = 'Logo (Featured Image)';
    $columns['link'] = 'Link';
    return $columns;
}

// This function is called for all columns.  It takes a string that's a column ID from the $columns
// array mentioned above.  The function should determine which column is being output and output the
// content of that column for the current post.  Note the column content should be OUTPUT, not
// returned.
function <prefix>_<post-type>_custom_columns( $column ) {
    global $post;

    // This gets all the custom meta for the post in an array.
    $meta = get_post_custom( $post->ID );

    switch( $column ) {
        case 'logo':
            if (has_post_thumbnail( $post->ID ) ) {
                // This returns an array containing url, width and height.
                $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'small' );
                // To access the URL of the thumbnail we need to use $image[0]
                printf( '<img src="%s" alt="" height="32px" />', $image[0]);
            }
        break;
        case 'link':
            if (isset($meta['link-url'])) {
                printf( '<a href="%1$s">%1$s</a>', $meta['link-url'][0]);
            }
        break;
    }
}

I’m indebted to Rev VooDoo and this WordPress support post for the idea. I hope I’ve refined it slightly and given a bit of insight into its workings.

Change the “Enter Title Here” for Custom Post Types

Custom post types in WordPress are a powerful feature. If you are creating one chances are you want to customise every aspect of the CPT’s look in the WordPress admin area from labels to messages.

If you ever need to change the “Enter Title Here” for Custom Post Types this little filter snippet allows just that when a user is adding a new post.

function cpt_enter_title_here( $title ){
    $screen = get_current_screen();
    if ( 'custom_post_type' == $screen->post_type ) {
        $title = 'Custom Post Type Title Text';
    }
    return $title;
}

add_filter( 'enter_title_here', 'cpt_enter_title_here' );

Source – http://flashingcursor.com/wordpress/change-the-enter-title-here-text-in-wordpress-963

Remove incorrect WordPress username message during login

Why would you want to remove incorrect WordPress username message during login? Well during login WordPress will notify you if the username or the password is incorrect, if a hacker knows the username they have successfully cracked the login process by 50%. Heres how to remove the message and stop those hackings from finding that information.


function failed_login() {
 return 'The login information you have entered is incorrect.';
}

add_filter('login_errors', 'failed_login');

Now with this in your functions file WordPress will replace the usual message with ‘The login information you have entered is incorrect.’ regardless if they manage to get the username or password correct.

Programmatically Create a WordPress Page, Post, or Custom Post Type

Programmatically creates a WordPress post based on the incoming parameters.
/**
 * Programmatically creates a WordPress post based on the incoming parameters.
 *
 * Note: This function may need some additional work if you're dealing with non-English languages.
 *
 * @param	string	$title		The title of the page as presented to the users
 * @param	string	$slug		The slug used to access the page via the URL
 * @param	string	$post_type	The type of post to create. Can be either 'page' or 'post'
 * @param	string	$template	The template to apply to the page.
 * @return	int			The ID of the page that was created. -1 if the page already exists.
 */
function wp_snippets_create_post( $title, $slug, $post_type, $template = null ) {

	// Initialize the page ID so we know if it's been created
	$page_id = -1;

	// If a post doesn't already exist with the specified title, create it
	if( null == wp_snippets_get_permalink_by_title( $slug, $post_type ) ) {

		$page_id = wp_insert_post(
			array(
				'comment_status'	=>	'open',
				'ping_status'		=>	'open',
				'post_author'		=>	1,			// Administrator is creating the page
				'post_title'		=>	$title,
				'post_name'		=>	strtolower( $slug ),
				'post_status'		=>	'publish',
				'post_type'		=>	strtolower( $post_type )
			)
		);

		// If a template is specified in the function arguments, let's apply it
		if( null != $template ) {
			update_post_meta( get_the_ID(), '_wp_page_template', $template );
		} // end if

	} // end if

	return $page_id;

} // end wp_snippets_create_post

/**
 * Determine if a post or page already exists with the specified title.
 *
 * Note: This function may need some additional work if you're dealing with non-English languages.
 *
 * @param	string	$title		The title used to check if the post exists.
 * @param	string	$post_type	The post type that we're checking (could be post, page, or a custom post type)
 * @return	string				The permalink to the post. Null if the post or page doesn't exist.
 */
function wp_snippets_get_permalink_by_title( $title, $post_type ) {

    // Initialize the permalink value
    $permalink = null;

    // Try to get the page by the incoming title
    $post = get_page_by_title( strtolower( $title ), OBJECT, $post_type );

    // If the post exists, then let's get its permalink
    if( null != $post ) {
        $permalink = get_permalink( $post-&gt;ID );
    } // end if

    return $permalink;

} // end wp_snippets_get_permalink_by_title

Disable WordPress Directory Browsing With Your Apache .htaccess File

This code snippet will disable WordPress directory browsing and stop people from seeing your directory contents directly.

In a default WordPress installation people can browse your core directories and see the file contents by pointing there browser at; (for example)

http://www.yourdomain.com/wp-content/uploads/

This may be handy for you as a developer, but do you really want people browsing your images and other files?

Disable WordPress Directory Browsing

Prevent this from happening by placing the following snippet into your .htaccess file in the root of your WordPress installation.

######## begin prevent directory browsing ########
Options All -Indexes
######## end prevent directory browsing ########

Now when people try to snoop your directory they will see the following;

https://advent.elliottrichmond.co.uk/wp-content/uploads/

Enjoy.

Handy WordPress Debugging and Logging in Development

This handy WordPress debugging and logging snippet during development will help no end when developing themes or plugins, it is always a good idea to have these switched on in the WordPress wp-config.php file.

Replace in wp-config.php

define('WP_DEBUG', false);

with

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

Then for helpful logging of values and arrays to the debug.log file add this snippet to the wp-config.php below the previous code:

if(!function_exists('_log')){
  function _log( $message ) {
    if( WP_DEBUG === true ){
      if( is_array( $message ) || is_object( $message ) ){
        error_log( print_r( $message, true ) );
      } else {
        error_log( $message );
      }
    }
  }
}

Then whenever you need to log anything use

_log( $somevalue );

Source – http://fuelyourcoding.com/simple-debugging-with-wordpress/

Hide a page if a user is not logged in

Sometimes you might want to hide a page if a user is not logged in. To do this you can use this simple snippet to call a page from within your theme folder called ‘not-logged-in.php’ but, remember this will call before the header, footer and the bits in between so the file that is called should contain the whole code for the page including the html, head and body; opening and closing tags.

<?php
/* Template Name: Only for logged in users */
if ( !is_user_logged_in()) {
get_template_part('not-logged-in');
exit(0);
}
get_header();
?>

the file that’s called might be something like this:

<!DOCTYPE HTML>
<html>
<head>
<title>Ooops! You need to login.</title>
</head>
<body>
<h1>To view this page you need to login.</h1>
</body>
</html>

source: Developing a WordPress site on a live url

Custom WordPress branded login and custom redirects

Do you need a custom WordPress branded login and custom redirects in the dashboard? This snippet will customise the standard WordPress login page, you will need to create a logo and change some of the url parameters to suit your needs. This would be an ideal snippet for a plugin.


// This snippet redirects the login logo upon click
add_filter( 'login_headerurl', 'my_custom_login_url' );
function my_custom_login_url($url) {
 return 'http://www.squareonemd.co.uk';
}

//This snippet allows you to change the logo you see when you login to WordPress(http://website.com/wp-admin). Just put the snippet in functions.php, and then add your login image to a folder called images in your theme folder.

function custom_login_logo() {
 echo '<style type="text/css">
 h1 a { background-image:url(http://www.squareonemd.co.uk/wproute/login-logo.png) !important; }
 </style>';
}
add_action('login_head', 'custom_login_logo');

//Change the alt text for login image
function change_wp_login_title()
{
 echo 'Square One Web and Design';
}add_filter('login_headertitle', 'change_wp_login_title');

//Change the footer link in the admin area
function remove_footer_admin () {
 echo 'Web site design and development by <a href="http://www.squareonemd.co.uk">Square One</a>.';
}
add_filter('admin_footer_text', 'remove_footer_admin');

//Change the header logo in the admin area
function custom_admin_logo() {
 echo '<style type="text/css">
 #header-logo { width:32px; height:32px; background-image: url(http://www.squareonemd.co.uk/wproute/admin-logo.png) !important; }
 </style>';
}
add_action('admin_head', 'custom_admin_logo');

How many more sleeps to go?

Tis the season for giving!! – Here at Square One we want to give all you lovely people a little WordPress something… so simply click on our WordPress advent calendar every day to reveal a useful WordPress code snippet. Or better still simply submit your email and you’ll get them delivered to your inbox daily – after all we know its a busy time of year but we wouldn’t want you to miss out on all of our 25 little gems!

Is it to early to say Merry Christmas?