search

Archives: Snippets | Page 8

Change the Login Page Logo and Link in WordPress

The following code lets you change the logo on the WordPress login page as well as the link it points to:

add_filter( 'login_headerurl', 'namespace_login_headerurl' );
function namespace_login_headerurl( $url ) {
    $url = home_url( '/' );
    return $url;
}

function namespace_login_headertitle( $title ) {
    $title = get_bloginfo( 'name' );
    return $title;
}
add_filter( 'login_headertitle', 'namespace_login_headertitle' );

function namespace_login_style() {
    echo '<style>.login h1 a { background-image: url( ' . get_template_directory_uri() . '/images/logo.png ) !important; }</style>';
}
add_action( 'login_head', 'namespace_login_style' );

For more login page security tips, see Hardening WordPress Security.

Show All Settings Page in WordPress Dashboard

This snippet does something neat – it adds an option under the Settings menu with a link named “All Settings” that shows a full list of all settings in the database related to your WordPress site.

The code below shows this option only to site administrators and hides it from other users.


function all_settings_link() {
   add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
}

add_action('admin_menu', 'all_settings_link');

For a broader WordPress overview, see What is WordPress?.

Check if Current Page Is a Parent or Child Page

WordPress has a built-in function to check if you are on a specific page:

if ( is_page(5) ) {
        // do some stuff
    }

Or whether the page is a child of a specific page:

if ( $post->post_parent == '5' ) {
        // do some stuff
    }

But there is no built-in WordPress function that checks both conditions together, and this is very useful. For example – if we want to load a JS file for a videos page and all pages under it…

The following function (add to functions.php) creates a new logical function for this check:

function is_tree($the_page_id) {   
    global $post;         

    if(is_page()&&($post->post_parent==$the_page_id||is_page($the_page_id))) 
       return true;   
    else 
       return false;   
    };

Usage

if (is_tree(5)) {
        // do some stuff
    }

For more on WordPress page templates, see WordPress Template Hierarchy.

Set Default Post Status to Private in WordPress

The following code lets you set the default post status on your WordPress site to Private.

<?php 
function default_posts_to_private()
{
	global $post;

	if ( $post->post_status == 'publish' ) {
		$visibility = 'public';
		$visibility_trans = __('Public');
	} elseif ( !empty( $post->post_password ) ) {
		$visibility = 'password';
		$visibility_trans = __('Password protected');
	} elseif ( $post->post_type == 'post' && is_sticky( $post->ID ) ) {
		$visibility = 'public';
		$visibility_trans = __('Public, Sticky');
	} else {
		$post->post_password = '';
		$visibility = 'private';
		$visibility_trans = __('Private');
	} 
?>

	<script type="text/javascript">
		(function($){
			try {
				$('#post-visibility-display').text('<?php echo $visibility_trans; ?>');
				$('#hidden-post-visibility').val('<?php echo $visibility; ?>');
				$('#visibility-radio-<?php echo $visibility; ?>').attr('checked', true);
			} catch(err){}
		}) (jQuery);
	</script>
	<?php
add_action( 'post_submitbox_misc_actions' , 'default_posts_to_private' );

This uses a WordPress hook. Learn more in WordPress Hooks Explained.

Register Multiple Taxonomies in One Function

When working on a project that requires creating multiple taxonomies, it makes sense to use this function rather than creating a separate function for each taxonomy. Put each taxonomy’s parameters in the array and the function handles the rest:

<?php
/**
 * Register Multiple Taxonomies
 *
 */
function register_multiple_taxonomies() {
    $taxonomies = array(
        array(
            'slug'         => 'job-department',
            'single_name'  => 'Department',
            'plural_name'  => 'Departments',
            'post_type'    => 'jobs',
            'rewrite'      => array( 'slug' => 'department' ),
        ),
        array(
            'slug'         => 'job-type',
            'single_name'  => 'Type',
            'plural_name'  => 'Types',
            'post_type'    => 'jobs',
            'hierarchical' => false,
        ),
        array(
            'slug'         => 'job-experience',
            'single_name'  => 'Min-Experience',
            'plural_name'  => 'Min-Experiences',
            'post_type'    => 'jobs',
        ),
    );
    foreach( $taxonomies as $taxonomy ) {
        $labels = array(
            'name' => $taxonomy['plural_name'],
            'singular_name' => $taxonomy['single_name'],
            'search_items' =>  'Search ' . $taxonomy['plural_name'],
            'all_items' => 'All ' . $taxonomy['plural_name'],
            'parent_item' => 'Parent ' . $taxonomy['single_name'],
            'parent_item_colon' => 'Parent ' . $taxonomy['single_name'] . ':',
            'edit_item' => 'Edit ' . $taxonomy['single_name'],
            'update_item' => 'Update ' . $taxonomy['single_name'],
            'add_new_item' => 'Add New ' . $taxonomy['single_name'],
            'new_item_name' => 'New ' . $taxonomy['single_name'] . ' Name',
            'menu_name' => $taxonomy['plural_name']
        );
        
        $rewrite = isset( $taxonomy['rewrite'] ) ? $taxonomy['rewrite'] : array( 'slug' => $taxonomy['slug'] );
        $hierarchical = isset( $taxonomy['hierarchical'] ) ? $taxonomy['hierarchical'] : true;
    
        register_taxonomy( $taxonomy['slug'], $taxonomy['post_type'], array(
            'hierarchical' => $hierarchical,
            'labels' => $labels,
            'show_ui' => true,
            'query_var' => true,
            'rewrite' => $rewrite,
        ));
    }
    
}
add_action( 'init', 'register_multiple_taxonomies' );

Split WordPress Loop Posts into Groups

In my last project I needed to split the WordPress loop into groups of three posts – so if there are nine posts, every three would be wrapped in a div. You can do this using a counter and checking inside the loop whether it is a multiple of 3, and if so, closing the div. To change the number of posts per group, change the number 3 on line 14. Here is the code:

<?php if ( have_posts() ) :
	$i = 0;
	while ( have_posts() ) : the_post();
		if ( $i % 3 == 0 ) { ?>
			<div>
	<?php } ?>
			<div class="single_item">
				<h2>
					<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>
					</a>
				</h2>
			</div>
	<?php $i ++;
		if ( $i % 3 == 0 ) { ?>
			</div>
	<?php } ?>

	<?php endwhile; ?>
	<?php
	if ( $i % 3 != 0 ) { ?>
		</div>
	<?php } ?>

<?php endif; ?>

For more loop customization, see Remove a Category from the Main Loop.

Limit WordPress Search to Post Titles Only

There are situations (quite common) where you want to limit WordPress search to titles only and not the post body text. To do this, add the following code to your functions.php file. For a more powerful search engine, see Relevanssi Better Search. Note that this function also applies to search performed from the WordPress dashboard.

/**
 * Search SQL filter for matching against post title only.
 *
 * @param   string      $search
 * @param   WP_Query    $wp_query
 */
function wpse_11826_search_by_title( $search, $wp_query ) {
    if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
        global $wpdb;

        $q = $wp_query->query_vars;
        $n = ! empty( $q['exact'] ) ? '' : '%';

        $search = array();

        foreach ( ( array ) $q['search_terms'] as $term )
            $search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );

        if ( ! is_user_logged_in() )
            $search[] = "$wpdb->posts.post_password = ''";

        $search = ' AND ' . implode( ' AND ', $search );
    }

    return $search;
}

add_filter( 'posts_search', 'wpse_11826_search_by_title', 10, 2 );

Change WordPress Auto-Save Interval

When you write a post, it is automatically saved as a draft every minute. If your browser crashes this lets you recover your work. You can change the time between saves by adding the following line to your wp-config.php file:

define( 'AUTOSAVE_INTERVAL', X);

Where X is the number of seconds between saves.

For more wp-config.php settings, see Optimize WordPress Configuration via wp-config.php.

Move the WordPress Admin Bar to the Bottom

How to change the position of the admin bar in WordPress?

More than once the WordPress admin bar has bothered me because it hid menus that were set to position:fixed in CSS. A few lines in functions.php and the admin bar moves to the bottom of the page:

<?php
function fb_move_admin_bar() { ?>
	<style type="text/css">
		body {
			margin-top: -28px;
			padding-bottom: 28px;
		}
		body.admin-bar #wphead {
			padding-top: 0;
		}
		body.admin-bar #footer {
			padding-bottom: 28px;
		}
		#wpadminbar {
			top: auto !important;
			bottom: 0;
		}
		#wpadminbar .quicklinks .menupop ul {
			bottom: 28px;
		}
	</style>
<?php }
add_action( 'admin_head', 'fb_move_admin_bar' );
add_action( 'wp_head', 'fb_move_admin_bar' );

For safe WordPress customizations, see What Are Child Themes and How to Use Them.

Savvy WordPress Development official logo