WP Code Snippets – kod-snippar till WordPress

Postad: 30 januari 2020 | No Comments
Lästid: < 1 minut

Här listar jag en massa matnyttiga kod-snippar till WordPress och jag fyller ständigt på om jag hittar någon extra intressant.

Nyast inlagda kommer överst!

Denna post innehåller kod-snippar som du kan använda. Det är alltid bra att ta en backup av din stilmall och funktionsfil innan.

WordPress logged out users: Redirect to different pages based on Body Class with php and jQuery

<?php
   $classes = get_body_class();
if (in_array('my-profile',$classes)   || in_array('page-id-2324',$classes)    ) {
 
if( ! is_user_logged_in() ) {
     ?>
  <script>
 window.location.href = "https://your_url.com/register/";
  </script>         
      
<?php
}} 
?>

Automatic link to blog post page – functions.php

// Generate Link to posts page
function archi_get_post_page_url() {
  if( 'page' == get_option( 'show_on_front' ) ) {
    return get_permalink( get_option('page_for_posts' ) );
  } else { return home_url();}
}

Klistra in nedanstående kod i tema-filen du vill ha länken.

<a href="<?php echo archi_get_post_page_url();?>">Back to all post page</a>

Only show on the last page if post is paginated – functions.php

<?php /* Only show on the last page if post is paginated */
global $page; global $numpages; if( $page == $numpages ) :?>
   <?php // put whatever you want here ?>
<?php endif;?>

alter_span_cat_count_output – functions.php

WordPress grundinställning är att sätta en parentes kring varje postnummer. Genom att ta bort denna och istället använda span-taggar blir det lättare att styla med CSS.

add_filter('wp_list_categories', 'alter_span_cat_count_output');
  function alter_span_cat_count_output($links) {
  $links = str_replace('</a> (', '</a> <span>', $links);
  $links = str_replace(')', '</span>', $links);
  return $links;
}

Additional Image size – functions.php

// Additional Image size
add_image_size('widescreen', 750, 425, false);
add_filter('image_size_names_choose','your_custom_image_sizes');
function your_custom_image_sizes($sizes) {
    return array_merge($sizes, array('widescreen' => 'Widescreen'));
}

Lägg till ovanstående i din functions.php för att ändra storleken på det du vill ändra. Läs mer i WordPress Codex för information om add_image_size()

Add Post Formats to Custom Post Types – functions.php

// add post-formats to post_type 'my_custom_post_type'
function prefix_custom_post_formats_setup() {
   add_post_type_support( 'my_custom_post_type', 'post-formats' );
}
add_action( 'init', 'prefix_custom_post_formats_setup' );

Glöm inte att använda namnet på prefix till ditt eget

Breadcrumbs – Functions.php

/**
 * Generate breadcrumbs
 * @author CodexWorld
 * @authorURL www.codexworld.com
 */
function get_breadcrumb() {
    echo '<a href="'.home_url().'" rel="nofollow">Home</a>';
    if (is_category() || is_single()) {
        echo "&nbsp;&#187;&nbsp;";
        the_category(' &bull; ');
            if (is_single()) {
                echo "&nbsp;&#187;&nbsp;";
                the_title();
            }
    } elseif (is_page()) {
        echo "&nbsp;&#187;&nbsp;";
        echo the_title();
    } elseif (is_search()) {
        echo "&nbsp;&#187;&nbsp;Search Results for... ";
        echo '"<em>';
        echo the_search_query();
        echo '</em>"';
    }
}

Du placerar nedanstående kod i din single.php och category.php där du vill att den ska visas, oftast högst upp. Du ser hur den fungerar högst upp denna sida. Styla med CSS.

<div class="breadcrumb"><?php get_breadcrumb(); ?></div>

Different excerpt length in posts and postformats – functions.php

function custom_excerpt_length($length) {
    global $post;
    if (has_post_format( 'quote' )) {
		return 28;
	} else {
		return 20;
	}
}
add_filter('excerpt_length', 'custom_excerpt_length', 999);

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' );

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;
}