WP Code Snippets

WordPress article
Postad: 30.01.2020 | Uppdaterad: 03.02.2020 | Lästid: 3 minuter

Här listar jag en massa code snippets och jag fyller ständigt på om jag hittar någon extra intressant


WP Debugger – wp-config.php

# Turns on PHP debugger
define( 'WP_DEBUG', true );
# Turns on CSS and JavaScript debugger
define( 'SCRIPT_DEBUG', true );

Enable WordPress cache – wp-config.php

# Enables WP cache
define( 'WP_CACHE', true );

Enable built-in database optimization – wp-config.php

# Turns on database optimization feature
define( 'WP_ALLOW_REPAIR', true );
När du väl har kört koden WP_ALLOW_REPAIR och får meddelande att allt är ok så måste du ta bort definitionen från wp-config.php.

Force SSL login – wp-config.php

# Forces SSL login
define( 'FORCE_SSL_ADMIN', true );

Manage post revisions – wp-config.php

# Completely disables post revisions
define( 'WP_POST_REVISIONS', false );
# Allows maximum 5 post revisions
define( 'WP_POST_REVISIONS', 5 );

Empty Trash Automatically – wp-config.php

define('EMPTY_TRASH_DAYS', 5 ); 

Increase Memory Limit – wp-config.php

define( 'WP_MEMORY_LIMIT', '256M' );
define( 'WP_MAX_MEMORY_LIMIT', '256M' );

Move JavaScript from Head to Footer – functions.php

function remove_head_scripts() {
	remove_action('wp_head', 'wp_print_scripts');
	remove_action('wp_head', 'wp_print_head_scripts', 9);
	remove_action('wp_head', 'wp_enqueue_scripts', 1);

	add_action('wp_footer', 'wp_print_scripts', 5);
	add_action('wp_footer', 'wp_enqueue_scripts', 5);
	add_action('wp_footer', 'wp_print_head_scripts', 5);
	}
	add_action( 'wp_enqueue_scripts', 'remove_head_scripts' );

Add Shortcodes to Widgets – functions.php

add_filter( 'widget_text', 'do_shortcode' );

Remove type tag from script and style – functions.php

add_filter('style_loader_tag', 'codeless_remove_type_attr', 10, 2);
    add_filter('script_loader_tag', 'codeless_remove_type_attr', 10, 2);
    function codeless_remove_type_attr($tag, $handle) {
        return preg_replace( "/type=['\"]text\/(javascript|css)['\"]/", '', $tag );
    }
För att denna funktion säkert ska fungera så bör man även kopiera in koden här under - support för HTML5 script och style.

Register support for HTML 5 for script and style – functions.php

add_action(
    'after_setup_theme',
    function() {
        add_theme_support( 'html5', [ 'script', 'style' ] );
    }
);

Disable WP generated image sizes (since Twenty Fifteen) – functions.php

function shapeSpace_disable_image_sizes($sizes) {
	unset($sizes['medium_large']); // disable medium-large size
	unset($sizes['1536x1536']);    // disable 2x medium-large size
	unset($sizes['2048x2048']);    // disable 2x large size
	return $sizes;
	}
add_action('intermediate_image_sizes_advanced', 'shapeSpace_disable_image_sizes');

Disable scaled image size – functions.php

add_filter('big_image_size_threshold', '__return_false');

Total Posts – functions.php

function wpb_total_posts() { 
$total = wp_count_posts()->publish;
return $total; 
} 
add_shortcode('total_posts','wpb_total_posts');

Short_code total post

[ total_posts ]

Protect Your Site from Malicious Requests – functions.php

global $user_ID; if($user_ID) {
    if(!current_user_can('administrator')) {
        if (strlen($_SERVER['REQUEST_URI']) > 255 ||
            stripos($_SERVER['REQUEST_URI'], "eval(") ||
            stripos($_SERVER['REQUEST_URI'], "CONCAT") ||
            stripos($_SERVER['REQUEST_URI'], "UNION+SELECT") ||
            stripos($_SERVER['REQUEST_URI'], "base64")) {
                @header("HTTP/1.1 414 Request-URI Too Long");
                @header("Status: 414 Request-URI Too Long");
                @header("Connection: Close");
                @exit;
        }
    }
}

Disable all widget areas – functions.php

function disable_all_widgets($sidebars_widgets) {
if (is_home())
  $sidebars_widgets = array(false);
  return $sidebars_widgets;
}
add_filter('sidebars_widgets', 'disable_all_widgets');

Add Highlight Search Terms – functions.php

function wps_highlight_results($text){
     if(is_search()){
     $sr = get_query_var('s');
     $keys = explode(" ",$sr);
     $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wps_highlight_results');
add_filter('the_title', 'wps_highlight_results');

add_action( 'pre_get_posts', 'wpse67626_exclude_posts_from_search' );
function wpse67626_exclude_posts_from_search( $query ) {
    if ( $query->is_main_query() && $query->is_search() ) {
        // Get an array of all page IDs with `get_all_page_ids()` function
        $query->set( 'post__not_in', get_all_page_ids() );
    }
}

Enhanched Search Queries to Google Analytics – functions.php

function emphasize( $content, $search_query ) {
    $keys = array_map( 'preg_quote', explode(" ", $search_query ) );
    return preg_replace( '/(' . implode('|', $keys ) .')/iu', '<strong class="search-excerpt">\0</strong>', $content );
}

Add Categories to Single Page – functions.php

add_filter('body_class','add_category_to_single');
  function add_category_to_single($classes) {
    if (is_single() ) {
      global $post;
      foreach((get_the_category($post->ID)) as $category) {
        // add category slug to the $classes array
        $classes[] = $category->category_nicename;
      }
    }
    // return the $classes array
    return $classes;
  }

Add a reset button to comment form – functions.php

	add_action ( 'comment_form','my_add_reset_btn' );
	function my_add_reset_btn() {
    ?>
    <div class="reset_btn">
    <input type="reset" value="<?php _e('Clear', ''); ?>"> <i class="icon-remove-circle-1"></i></div>
	<?php
	}

Prevent Search Bots from Indexing Search Results – functions.php

if(is_search()) { ?>
 <meta name="robots" content="noindex, nofollow" />
<?php }?>

Redirect New Registered Users to a Specific Page – functions.php

function wps_registration_redirect(){
return home_url( '/finished/' );
}
add_filter( 'registration_redirect', 'wps_registration_redirect' );

Which Browser are Your WordPress Visitors Using – functions.php

add_filter('body_class','browser_body_class');
function browser_body_class($classes) {
global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
if($is_lynx) $classes[] = 'lynx';
elseif($is_gecko) $classes[] = 'gecko';
elseif($is_opera) $classes[] = 'opera';
elseif($is_NS4) $classes[] = 'ns4';
elseif($is_safari) $classes[] = 'safari';
elseif($is_chrome) $classes[] = 'chrome';
elseif($is_IE) $classes[] = 'ie';
else $classes[] = 'unknown';
if($is_iphone) $classes[] = 'iphone';
return $classes;
}

Show Chosen Results on the Search Results Page – functions.php

function limit_posts_per_search_page() {
	if ( is_search() )
		set_query_var('posts_per_archive_page', 20); 
}
add_filter('pre_get_posts', 'limit_posts_per_search_page');

Hide or Remove Categories from a Homepage – functions.php

function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-5, -34' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );

Remove autop – functions.php

function filter_ptags_on_images($content){
   return preg_replace('?/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}
add_filter('the_content', 'filter_ptags_on_images');

Remove default widgets from dashboard – functions.php

// Create the function to use in the action hook
function example_remove_dashboard_widgets() {
	// Globalize the metaboxes array, this holds all the widgets for wp-admin
 
	global $wp_meta_boxes;
 
	// Remove the incomming links widget
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);	
 
	// Remove right now
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
	unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
	unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
}
 
// Hoook into the 'wp_dashboard_setup' action to register our function
add_action('wp_dashboard_setup', 'example_remove_dashboard_widgets' );

Change the Dashboard Footer Text – functions.php

function remove_footer_admin () {
    echo "Your text";
} 
add_filter('admin_footer_text', 'remove_footer_admin');

Post Archive Pagination – page.php

<?php
the_posts_pagination(  array(
'mid_size' => 5, // The number of pages displayed in the menu.
'prev_text' => __( '&laquo; Go Back', 'textdomain' ), // Previous  Posts text.
'next_text' => __( 'Move Forward &raquo;', 'textdomain' ), // Next  Posts text.
) );
?>

Sharpen Uploaded Images when Resized – functions.php

function ajx_sharpen_resized_files( $resized_file ) {

    $image = wp_load_image( $resized_file );
    if ( !is_resource( $image ) )
        return new WP_Error( 'error_loading_image', $image, $file );

    $size = @getimagesize( $resized_file );
    if ( !$size )
        return new WP_Error('invalid_image', __('Could not read image size'), $file);
    list($orig_w, $orig_h, $orig_type) = $size;

    switch ( $orig_type ) {
        case IMAGETYPE_JPEG:
            $matrix = array(
                array(-1, -1, -1),
                array(-1, 16, -1),
                array(-1, -1, -1),
            );

            $divisor = array_sum(array_map('array_sum', $matrix));
            $offset = 0; 
            imageconvolution($image, $matrix, $divisor, $offset);
            imagejpeg($image, $resized_file,apply_filters( 'jpeg_quality', 90, 'edit_image' ));
            break;
        case IMAGETYPE_PNG:
            return $resized_file;
        case IMAGETYPE_GIF:
            return $resized_file;
    }

    return $resized_file;
}   

add_filter('image_make_intermediate_size', 'ajx_sharpen_resized_files',900);

Remove Unneeded Images / Thumbnail Sizes

update_option( 'thumbnail_size_h', 0 );
update_option( 'thumbnail_size_w', 0 );
update_option( 'medium_size_h', 0 );
update_option( 'medium_size_w', 0 );
update_option( 'large_size_h', 0 );
update_option( 'large_size_w', 0 );

Show random posts on front page – functions.php

add_action('pre_get_posts','alter_query');
function alter_query($query){
    if ($query->is_main_query() &&  is_home())
        $query->set('orderby', 'rand'); //Set the order to random
}

Limit The Post Title in WordPress by Word Count – functions.php

// limit the post title in wordpress by word count
function wcs_limit_word_count_in_post_title( $title ) {
    return wp_trim_words( $title, 10, '' );
}
add_filter( 'the_title', 'wcs_limit_word_count_in_post_title' );
<?php
    echo wp_trim_words( get_the_title(), 10, '' );
?>

How to Redirect to Custom Page After Registration – functions.php

// redirect to custom page after registration
function wcs_registration_redirect() {
    return home_url( '/welcome-page' );
}
add_filter( 'registration_redirect', 'wcs_registration_redirect' );

Shorten excerpts – functions.php

Function new_excerpt_length($trength) {return 20;}
add_filter(‘excerpt_length’,’new_excerpt_length’);

Remove WordPress Version From the Footer – functions.php

remove_action('wp_head', 'wp_generator');
function lb_remove_version() {
return '';
}
add_filter('the_generator', 'lb_remove_version');

Remove Bloat From Database – functions.php

function remove_default_userfields( $contactmethods ) {
unset($contactmethods['aim']);
unset($contactmethods['jabber']);
unset($contactmethods['yim']);
return $contactmethods;
}
add_filter('user_contactmethods','remove_default_userfields',10,1);

Get rid of the emojies

remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );

Allow PHP in WordPress text widgets – functions.php

add_filter('widget_text', 'enable_php_code', 99);
function enable_php_code ($text) {
if (strpos($text, '<' . '?') !== false) { ob_start(); eval('?' . '>' . $text);
$text = ob_get_contents();
ob_end_clean();
}
return $text;
}

Move WordPress admin bar to bottom – functions.php

function fb_move_admin_bar() {
echo '';
}
// on backend area
add_action( 'admin_head', 'fb_move_admin_bar' );
// on frontend area
add_action( 'wp_head', 'fb_move_admin_bar' );

Exclude category from feeds – functions.php

// custom feed query
function customFeedquery($query) {
	if(is_feed()) {
		$query->set('cat','-8'); // this exclude category 8
		return $query;
	}
}
add_filter('pre_get_posts', 'customFeedquery');

Creating a shortcode – functions.php

<?php
function myplugin_my_shortcode( $atts = array(), $content = '' ) { 
  echo "This is some shortcode output";
}
add_shortcode('my-shortcode','myplugin_my_shortcode');

Mark Comments with Very Long URLs as Spam – functions.php

<?php
  function lb_url_spamcheck( $approved , $commentdata ) {
    return ( strlen( $commentdata['comment_author_url'] ) > 50 ) ? 'spam' : $approved;
  }
  add_filter( 'pre_comment_approved', 'lb_url_spamcheck', 99, 2 );
?>

Remove Auto Linking of URLs in WordPress Comments – functions.php

remove_filter('comment_text', 'make_clickable', 9);

Redirect To Post If Search Results Return Only One Post – functions.php

add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
            exit;
        }
    }
}

Automatically Add a Search Box to Your Nav Menu – functions.php

add_filter('wp_nav_menu_items','add_search_box', 10, 2); 
function add_search_box($items, $args) { 
	ob_start(); 
	get_search_form(); 
	$searchform = ob_get_contents(); 
	ob_end_clean(); 
	$items .= '<li>' . $searchform . '</li>'; 
	return $items; 
}

Insert an Author Box – functions.php

<?php echo get_avatar( get_the_author_email(), '80' ); ?>
<?php the_author_meta( "display_name" ); ?> 
<?php the_author_meta( "user_description" ); ?> 
<?php if (get_the_author_url()) { ?><a href="<?phpthe_author_url(); ?>">Visit <?php the_author(); ?>'s website</a><?php }else { } ?>

Hide Login Errors in WordPress – functions.php

function no_wordpress_errors(){
  return 'Something is wrong!';
}
add_filter( 'login_errors', 'no_wordpress_errors' );

Add Odd and Even CSS Classes to WordPress Posts – functions.php

function oddeven_post_class ( $classes ) {
   global $current_class;
   $classes[] = $current_class;
   $current_class = ($current_class == 'odd') ? 'even' : 'odd';
   return $classes;
}
add_filter ( 'post_class' , 'oddeven_post_class' );
global $current_class;
$current_class = 'odd';
.even {
background:#f0f8ff;  
} 
.odd {
 background:#f4f4fb;
}