[tutorial] Chris’s custom optimizations for functions.php, etc.

Posted in: Newsmag
Post count: 9544

For those who want to ‘speed tune’ for fastest page load time, separate from any pagespeed insights score, removing Google Fonts is a must ….

————-
I love OpenSans …

however for our new project (not using this theme), we actually chose NOT to use any Google fonts for page speed, not “rating” but actual page load time.

I’ve been tuning one project down from 1.9 sec with default theme, to 1.1 seconds (so far), with image, with https, with mod_pagespeed, but not yet using caching plugin …

for this project I’m using a web safe font stack like so in place of (sigh) Open Sans:

font-family: 'Segoe UI', Frutiger, 'Frutiger Linotype', 'Dejavu Sans', 'Helvetica Neue', Arial, sans-serif;

for the “alt” font, using this stack
'Franklin Gothic Medium', 'Franklin Gothic', 'ITC Franklin Gothic', Arial, sans-serif;

I’m “getting used to it …” 🙂

For those interested, nice roundup of web safe “font stacks” here:
http://www.cssfontstack.com/

Post count: 25

Hello Chris, thank you for sharing valuable information. Here is something that could help with page speed:
I use a plugin called “Plugin Organizer” https://wordpress.org/plugins/plugin-organizer/ to enable and disable plugins per post/page. For instance I enable Visual Composer on homepage and on few other pages where it is needed and disable it on the rest of the website. Most plugins that I use work only on admin panel anyway so they can be safely disabled on posts and pages. This should help speeding up the website as well. I hope you will find this information useful.
Kind regards

Post count: 9544

Hi
it’s better to implement the hooks into the functions.php file vs adding another plugin (my opinion only).

Reason is latency, additional php overhead, and possibility of plugin introducing issues if not updated with new versions of php, wordpress, other plugins, etc.

However, if it works for you, that’s great.

Always best to add your own functions if possible, which is at least how we do it over here.

Any plugin that loads admin only CSS/JS functions on your posts/pages code, is a bad plugin where that should only be hooked into the admin panel and not your posts/pages, btw.

There is a simple function to remove VC from loading on post/pages, which we use, also.

Post count: 9544

Hi
I am no longer active in this forum, but another person appears to have tweaked/updated the remove VC code for functions.php, which is outlined here:

https://forum.tagdiv.com/topic/disabling-visual-composer-makes-my-website-go-error-500/

and you can always ask TagDiv for the best way to do that with latest versions of themes, which continue to evolve.

Chris

Post count: 22421

Hello,

For further questions on this thread, please create a new topic and we will get back to your as soon as possible.

Thank you!

Post count: 9544

Just a quick follow up for old timey sake, for those coming late to this party:

IMAGE COMPRESSION

QUICK TIPS:
Test a post page with GTMetrix.com — this will show you what you need to do to improve speed specifically, for example giving you examples you can download of optimized images for the post page you test to see how that impacts you.

Also, to compress thumbnails, you can change the default compression per my guide in your wp-config file, then “regenerate thumbnails” to make smaller versions. (AND: you should be backing up your site before you mess with it, obviously!)

Alternate advanced method of compression:
download complete image folder to your PC via FTP for backup then use one of the various PC software apps to compress/process all images, then re-upload via FTP. Here is one for Windows, as just one of many examples: http://icompressor.blogspot.in/

Or, if that makes no sense or is too difficult; make backup first, then try this nifty plugin, which is a PAID service after the first 100 images; but useful to test if it works for you:
https://wordpress.org/plugins/tiny-compress-images/

Post count: 9544

NEWSMAG OPTIMIZATION EFFORT 2016
——————————-
PRECIS:
* WordPress 4.6
* Newsmag 3.1
* tagDiv Composer v1.0 BETA
* TD Speed Booster plugin – Version: 4.5
——————————-
I am re-optimizing my network sites since upgrading from v2 v3, and needing to revisit all the past steps from past 3 years with new TadDiv tech, code, etc.

This project presumes I will do several advanced things
1) run mod_pagespeed on deploy; currently disabled for all other efforts; with proper webp format support added as mime type and in htaccess (MPS converts some png files to base64 inline, and others to .webp format when better than jpeg)
2) compress main css and js files not already compressed after ‘thinning’
3) decomment some TD files loaded by pages which are (ahem) overly commented
4) have proper gzip/deflate/TTL elements on server
5) no caching used for initial deploy (MPS uses opcache/memcache)
6) move CSS to footer and use critical CSS generator for inline above the fold CSS
7) test free SSL cert and http/2 on our new server for 2017
8) test move to PHP7 from PHP5

Follow along if the mood strikes; I’m just sharing my info not offering to consult with you (you cannot afford me, in most cases). Please do not post any questions until I post the info during last half of August 2016, as you can “try” any of my changes if you wish, at your own risk.

I am using Unix/Linux, CentOS, Plesk 12.5x (will likely move to ONYX when releases for 2017); Apache with NGINX in front; dedicated server, 1GB connection to network in Class A datacenter in Texas, USA. Running PHP 5x with PHP7 installed and will test ‘7’ once initial deploy stable with my ‘thinning’ and optimization.

Hey party people, it’s on!

  • This reply was modified 9 years by simchris.
Post count: 9544

REV ONE “thinning” a couple of files to re-orient myself on where things are, what they do, etc. — very minor fixes since we do not use the following on our news portals
* WooCommerce
* BBpress
* BuddyPress

=========== THINNING EFFORT PART ONE =============

THINNING BY CHRIS SIMMONS – A QUICKIE NEWSMAG 3.1 TUTORIAL
make backups while editing; you assume all risk for edits. If what I’m doing does not make sense, then stop right now or you might wreck it (check yourself before you wreck yourself) 🙂

<< Edits must be made each theme update if files change! >>

//******
theme/style.css

Remove bbpress and buddypress sections

(save 50kb before compression)

//******
theme/functions.php

(1)
line 17
remove woocommerce and bbpress stuff not used

(saves 2kb prior to compression)

//******
/includes/wp_booster/td_wp_booster_functions.php

(1)
line 187, remove woocommerce support

(2)
Remove editor styles
new line 814

(3)

Remove echo scripts/theme info
new line 827

(saves 0 KB in file)

//*******

END EFFORT ONE

THESE MISSIVES ARE COPR. © Christopher Simmons, all rights reserved. You may use this info, but you may *NOT* republish on your blog, in a book, or make claim any of this is originated by you. Seriously. I know warlocks and they can get bitchy.

Post count: 9544

UPDATED FUNCTIONS HAXX AUG 2016
— supercedes old and moldy stuff in this long thread

Works for me on Apache; if not for you, then you messed something up elsewhere.

This goes at BOTTOM of the /theme/functions.php file

Don’t know where that is, then stop right now, buddy. Learn to use FTP!

/** ========================================== */

/** CUSTOM OPTIM CODE : by Christopher Simmons - REV 8.17.16 */

// Remove jQuery Migrate Script from header and Load jQuery from Google API
function simmonsbunny_remove_jquery_migrate_load_google_hosted_jquery() {
	if (!is_admin()) {
		wp_deregister_script('jquery');
		wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', false, null);
		wp_enqueue_script('jquery');
	}
}
add_action('init', 'simmonsbunny_remove_jquery_migrate_load_google_hosted_jquery');

add_action('init', 'cng_author_base');
function cng_author_base() {
    global $wp_rewrite;
    $author_slug = 'profile'; // change slug name
    $wp_rewrite->author_base = $author_slug;
}

add_filter( 'jpeg_quality', create_function( '', 'return 50;' ) );

/** functions for headcleaner */
function rm_generator_filter() { return ''; }
add_filter('the_generator', 'rm_generator_filter');

remove_action('wp_head','wlwmanifest_link');
remove_action('wp_head','rsd_link');
remove_action('wp_head','feed_links', 2);
remove_action('wp_head','feed_links_extra', 3);
remove_action('wp_head','start_post_rel_link', 10, 0);
remove_action('wp_head','adjacent_posts_rel_link_wp_head', 10, 0);
remove_action('wp_head','print_emoji_detection_script',7);
remove_action('wp_print_styles','print_emoji_styles');

function remove_cssjs_ver( $src ) {
 if( strpos( $src, '?ver=' ) )
	 $src = remove_query_arg( 'ver', $src );
 return $src;
}
add_filter( 'style_loader_src', 'remove_cssjs_ver', 10, 2 );
add_filter( 'script_loader_src', 'remove_cssjs_ver', 10, 2 );

function remove_pingback_url( $output, $show ) {
  if ( $show == 'pingback_url' ) $output = '';
  return $output;
}
add_filter( 'bloginfo_url', 'remove_pingback_url', 10, 2 );

/** functions for security */
function no_errors_please(){
return 'You appear to be up to no good. Your IP logged and will be blocked.';
}
add_filter( 'login_errors', 'no_errors_please' );

function disable_reset_lost_password()
 {
   return false;
 }
add_filter( 'allow_password_reset', 'disable_reset_lost_password');

function remove_lost_your_password($text)
  {
    return str_replace( array('Lost your password?', 'Lost your password'), '', trim($text, '?') );
  }
 add_filter( 'gettext', 'remove_lost_your_password'  );

add_filter( 'send_email_change_email', '__return_false' );

/** functions for admin bar */
function mytheme_admin_bar_render() {
  	global $wp_admin_bar;
  	$wp_admin_bar->remove_menu('wpseo-menu');
  }
 add_action( 'wp_before_admin_bar_render', 'mytheme_admin_bar_render' );
 add_filter( 'wpseo_use_page_analysis', '__return_false' );

function my_custom_css() {
     echo '<style>
          .misc-pub-section.yoast-seo-score.content-score { display: none; }
          .misc-pub-section.yoast-seo-score.keyword-score { display: none; }
     </style>';
}
add_action( 'admin_head', 'my_custom_css' );

function dequeue_yoast_css() {
  wp_dequeue_style('yoast-seo-adminbar');
  wp_deregister_style('yoast-seo-adminbar');
}
add_action('wp_enqueue_scripts','dequeue_yoast_css');

/*remove embeds */
function disable_embeds_init() {
remove_action('rest_api_init', 'wp_oembed_register_route');
remove_filter('oembed_dataparse', 'wp_filter_oembed_result', 10);
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');
}
add_action('init', 'disable_embeds_init', 9999);

function project_dequeue_unnecessary_scripts() {
wp_dequeue_script( 'comment-reply' );
wp_deregister_script( 'comment-reply' );
}
add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts',100 );

/** End Christopher's magic bunny code; Copr. (c) 2013-2016 CLS */

========== and again ===============
THESE MISSIVES ARE COPR. © Christopher Simmons, all rights reserved. You may use this info, but you may *NOT* republish on your blog, in a book, or make claim any of this is originated by you. Seriously. I know warlocks and they can get bitchy.

  • This reply was modified 9 years by simchris.
Post count: 9544

CAUTION:
note in my functions.php example above/prior post I have this section which you may not need; I use this for changing the author slug to profile for specific site; but not needed for most folks and you would also need to update the templates for Newsmag to point to /profile/ vs /author/.

This section near top likely NOT useful to most folks and can be removed:
add_action('init', 'cng_author_base');
function cng_author_base() {
global $wp_rewrite;
$author_slug = 'profile'; // change slug name
$wp_rewrite->author_base = $author_slug;
}

Post count: 9544

So, I want to remove Google fonts, stop them being loaded in page head, and use default mobile friendly font stack, also works for desktop:

——- PART 2 / FONT SWAP;
remove default Google Fonts in theme and loaded externally ——–

**/theme/includes/td_config.php

/remove google font calls for defalt roboto and open sans

lines 3247-3259 — remove:

/**
* the default fonts used by the theme. For a list of fonts ids @see td_fonts::$font_names_google_list
*/
td_global::$default_google_fonts_list = array (
'438' => array(
'css_style_id' => 'google_font_open_sans',
'url' => td_global::$http_or_https . '://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700'
),
'522' => array(
'css_style_id' => 'google_font_roboto_cond',
'url' => td_global::$http_or_https . '://fonts.googleapis.com/css?family=Roboto:400,300,700,700italic,400italic,300italic'
),
);

**/theme/style.css v3.1

<< do search/replace for ‘string’ using text editor like BBEdit, TextPad, etc.) >>

lines 352 + 866 + 962 + 1663 + 1752 + 1861 + 2608 + 5355 + 5388 + 5450 + 5691 + 5734 + 7303 + 7340 + 7565 + 7608 ((ETC.)),
replace: font-family: 'Open Sans', arial, sans-serif;

with modern font stack:
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;

lines 379 + 387 + 473 + 1968 + 2006 + 2118 + 2160 + 2301 + 2625 + 7500 ((ETC.)),
replace: font-family: 'Roboto', sans-serif;

as above, same font stack, or choose a serif stack for replacing Roboto.

this isn’t best choice, but option:

font-family: Rockwell, Georgia, Times, "Times New Roman", serif;

======
REMINDER: these haxx need to be done EVERY theme update; keep record and backup of your files in sub-folder on your work PC/Mac to easily redo this as needed for future versions of Newsmag (if you want… or not, won’t matter to me either way … just sayin….) 🙂

Post count: 9544

okay; just noticed after forcing all remaining .js to footer, the deqeue comment-reply in my functions.php code above not working; however corrected, this does:

// Remove comment-reply.min.js from footer
function chrisbunny_clean_header_hook(){
wp_deregister_script( 'comment-reply' );
}
add_action('init','chrisbunny_clean_header_hook');

Post count: 9544

For those curious about baseline speed with GTmetrix for test bed:

No additional compression of css or js done (minification);
No caching plugin running;
Mod_pagespeed is OFF;
Page has no ad, but large image, sidebar, bottom bar images; large logo.
Default Newsmag theme (not using a “style/demo”).
Share buttons ‘on’ at top of page.

Pagespeed Score: A (96%)
YSLOW Score A (94%)
Page load time: 1.2s
Total Page size: 248kb
requests: 12

Nice.

Still to do:
figure out how to fix the wonky ? query on the newsmag icon font …
/images/icons/newsmag.woff?11

a) compress style.css
b) replace gravatar with local author image
c) main css to footer; preload critical CSS in head (fixes ‘render blocking …’)
d) enable mod_pagespeed – does on the fly comment removal, image optiization for small png to base64 or webp, removes all double spaces in text for pseudo-minification; further optimizes anything loaded from google like jquery

=========
that’s it for now.
Hope this isn’t annoying folks too much 😉

————
Radu and co have really done a great job on this and theme is speedy on desktop testing ‘as advertised …” which is awesome. I was worried going from v2 to v3 was going to bring bloaty-mcbloatface, and turns out – not so much 🙂

  • This reply was modified 9 years by simchris.
Post count: 9544

Okay … super annoying for those of us NOT using emoji or google fonts, WP 4.6 “helpfully” added a dns prefetch for the stupid emoji (seriously)….

so anybody else head cleaning, will need to update their emoji cleaner like so:

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

Post count: 171

You should update the whole code. I got lost with the last bit of code. Didnt know what to replace in the original you put a few posts before. :p

BTW, I use Better WordPress Minify, it works very well with the minify and merge thing, but Google still tell me to move the minifed file to the bottom. Is there any way to do this without the TagDiv Speed Booster plugin? That dont work for me cos it has like a delay or something while loading my settings (font, colors, menu position).
Tanx in advabnce.

  • This reply was modified 9 years by Arved007.
Post count: 9544

Hey!
I’ll post updated version once I finish the tweak of doom! Have been messing with the new TD Composer beta, so got sidetracked, as I wanted to leave VC behind entirely from “now” onward.

I will actually update and add the #comments on what couple of the things actually do. And I’ll include my AMP footer injection code, too!

Actually the trick with the stupid render blocking thing is three step

a) generate ‘critical CSS’ for your post page; insert this into the header.php right before </head>

b) in functions.php – “de-enqueue” the main style.css from being generated and placed in the head.

c) put link to the main style.css file in the footer.php file.

d) if you don’t want to use functions.php to move the other .js stuff; use the “Scripts to Footer” WP plugin.

THAT is the super secret way we do it for my SEO service here (not a sales pitch). What this does is load the important CSS “above the fold” inline, then page loads on mobile (and I have 98 MPS score to prove it; the last gotcha is the CSS for stupid ‘tap targets’ — ugh) without waiting for anything, then main CSS loaded at end.

This simply works. If you have weirdo plugins injecting css and js in the head, you’ll have to de-enqueue them and move to footer.php manually. But the speed rating improvement is insane as there is literally *no* “render blocking” of any kind for Google on mobile or desktop. Period.

I was writing an ebook on all of this but personal life intruded so that didn’t happen.

  • This reply was modified 9 years by simchris.
Post count: 89

Hi Chris, was reading an interesting article today where they mention prefetching dns for google analytics and also google fonts.. do you think this is something to add or no?
Here’s a link to that article: https://www.keycdn.com/blog/speed-up-wordpress/

Post count: 9544

Yes, we do that with mod_pagespeed automatically, so we don’t need to add that here manually and for the current projects I’m doing for our news portals we don’t use either GA or Google Fonts for better page speed; but yes, if you are using anything like that, it does help. (HINT: use a web host that supports mod_pagespeed — it helps WordPress in so many ways; DNS pre-fetch, convert some images to webp for mobile, remove whitespaces (double spaces and pesky indents), remove comments!, DNS prefetch, etc.).

Post count: 152

So, I want to remove Google fonts, stop them being loaded in page head, and use default mobile friendly font stack, also works for desktop:

——- PART 2 / FONT SWAP;
remove default Google Fonts in theme and loaded externally ——–

Should i apply Part 1? and where is the part 1?

  • This reply was modified 9 years by Syams.
Post count: 9544

Part 2, is “part 2” of my most recent modifications. Part one was Aug 17, 2016 🙂

“Part 2” only covers removing Google Fonts entirely from v3.1.

Have not gotten to part3 ; we have issue with trying to get latest version of mod_pagespeed running as it generates errors on any site with “missing images” — and from our recent server crash, that happens on several sites; so having to put in rewrite matches to a default image, which seems like a good practice anyway, so going to add that to my htaccess example which I will update soon. Pain.

Post count: 31

where to put your .htaccess code? After this?

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Post count: 9544

@contatolab

Hi!
In my case I tend to put anything directed at server before WordPress stuff, like the mod_pagespeed stuff if required, or any funky stuff like force 301 redirect for non-https to https, or custom rewrites to fix old icky permalinks (like we had horrible stuff like /2005/16/03/enc235-name-of-story_123345.php !!!).

Then WordPress block

then the add handler types, as applicable, time to live, and in my case I don’t use XMLRPC and redirect that.

So:

[ custom stuff ]
[ wordpress stuff ]
[ add handler for new types like webp, or woff2 ]
[ time to live, expiration stuff ]
[ redirect xmlrpc ]

And I suppose if your server “requires” you to put in the deflate stuff, I personally would put that with the add handler stuff area.

Put another way, I put stuff that does rewrites before WordPress stuff, and everything else after. 🙂

🙂

Post count: 217

Hi Chris,

thanks for your great tipps. One question…how can I find out what the “critical CSS is”, to put it in the header?

Thank you! 🙂

Post count: 9544

I use a critical CSS generator that scans the page and generates that for me. I honestly forget which one we use; started with free version of something, now use a paid version of something. Might have to Google that until I go find it (I don’t use it everyday, obviously).

In midst of merging 13,000 articles from our old CMS on main website into WordPress using a paid plugin that lines up old category IDs with new ones, imports user accounts as authors in new system, etc. Very neat that so many companies build awesome importers to merge legacy 2004/5 era CMS stuff into modern WP dbase. Did that same with our main ecom system last year, too with another company.

Anyway… that was the quick and dirty answer this morning.

Google: “Critical CSS Generator” to find it. 🙂

Post count: 436

Hey Chris.

Hope you are doing great 🙂

Today, I thought to look for any previous thread on keyword “plugin organiser” and then I was sent here 🙂

Actually, I am looking for a way to keep using “mobile theme plugin” while still being able to use Visual composer based page on some pages. I asked the same question here: https://forum.tagdiv.com/topic/how-can-i-use-visual-composer-on-specific-page-on-mobile-theme/ . I think that “Plugin organiser” can help me to achieve this result.

But here when I read this, I agree that we must try to avoid using any new plugins. So, is there any way to achieve this ( enabling visual composer on the certain page even when I am using TagDiv mobile theme plugin or disabling mobile theme plugin on certain page/post ) using few codes under functions.php ?

    PS: I know everything is possible when a developer puts his mind into it, but I just want to know if it’s possible to do with few codes so that I can do it by myself too.

Thank you

Viewing 25 posts - 126 through 150 (of 182 total)
You must be logged in to reply to this topic.