How to inline the contents of an entire stylesheet with Wordpress? - php

I'm using Wordpress, but this question could probably apply to other PHP-driven templating system.
I'd like to have a css file (i.e. critical.css) that contains all the styles for important global elements & above-the-fold content (e.g. typography, header includes, navigation, site-wide banners/heros), kept separate from my modular content, page-specific styles & footer styles. I then want to take the contents of this file and print it between style tags right below the document title tag.
The goal is to improve above-the-fold rendering speed. I've noticed a definite improvement in the rendering of above-the-fold content when those styles are prioritized (along with any resets), even if those improvements are more experiential than technical.
But...I'm having trouble figuring out how to "print" the inline styles from this document into the wp_head.
I've explored wp_add_inline_style and this does not seem to offer the functionality I'll need. It appears you have to define those styles within a function, and that's definitely not what I'm going after.
Does there exist a method for hooking inline styles taken from my critical.css file into the wp_head? wp_print_styles is either deprecated or not recommended according to the Codex.
If not, what is the preferred method of emphasizing these critical styles in Wordpress? Preferably, a method that's not render-blocking or doesn't rely on a metabox.
I'm trying to avoid using a PHP include (i.e. dumping everything between PHP tags in a critical-styles.php file and then calling that in the wp_head) in favor of something cleaner or that can be achieved with functions.php or Wordpress's native hooks. With all the emphasis on Pagespeed optimization these days, I was surprised that this hadn't been asked here in a Wordpress context. Any help on this or methods that have worked better for you are greatly appreciated.

You can simply include the actual CSS file in header.php:
<style>
<?php include 'path/to/critical.css'; ?>
</style>
PHP's include() function doesn't require that the included file also has to be PHP.
Alternatively, if you want to keep things in functions.php, you could do a file_get_contents() and hook into the wp_head action hook:
function hook_critical_css() {
$critical_css = file_get_contents( 'path/to/critical.css' );
echo '<style>' . $critical_css . '</style>';
}
add_action('wp_head','hook_critical_css');

Related

How to load local font in php instead of google font with Variable

With the GDPR hitting hard I have to remove google fonts that are loaded per Link from Google Servers.
I have a wordpress theme that has those links everwhere.
I am not very good at php, but in this theme I have this link:
$open_sans_font_url = "https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,300,400,600&subset=$subsets&display=fallback";
}
I puts the loaded font into a var. I need to change this so it will load the font from my local font folder.
The problem is, I don't know how to change the link in a way that it will load all the font and font weights/styles. Is it possible? And maybe it is easy but I can't change the whole php file - not enough knowledge from my side and I don't want to risk destroying the theme.
(I know about #font-face and css but not how to add as a link in a var)
I appreciate any help - thank you!
It's not possible to simply replace the variable since it links to a CSS file. There's two options on what you can do. Due to the lack of more code, I can only describe how to do this and not provide direct examples.
Method one: Using your existing CSS, remove the variable
You can add the OpenSans font to your own CSS with the mentioned #font-face, and then remove where the $open_sans_font_url variable is used.
It's likely that this variable is only used to create a <link rel="stylesheet" href="..."> tag to include the Google Font. If you remove this stylesheet inclusion and other possible usages of the variable, you're no longer using Google Fonts.
Method two: Use your own CSS file with the font-face
For this, you need to create your own CSS file, for example opensans.css, with the font-face loaded in. You can then use the Wordpress function get_template_directory_uri() to get the address of your new CSS file within the theme like this:
$open_sans_font_url = get_template_directory_uri() . '/opensans.css';
I hope this helps!
I had the same issue and I solved it by switching to BunnyCDN Fonts, a clone of Google Fonts that (unlike Google Fonts) process requests completely anonymously.
https://fonts.bunny.net
https://css-tricks.com/bunny-fonts/

How to NOT write file_put_contents on EVERY page load

I am completely new to PHP (2 weeks) and I have created a simply script for Joomla that will save parameters from my my admin area options and put those values into a CSS format and save the file. It's a whole long script of CSS but here's an example of it...
<?php
ob_start();
?>
<?php
////////////// Custom colours set from the admin panel
if ($this->params->get('templateColor'))
{
?>
/* <?php echo($template); ?>: Custom Auto-Generated CSS Colors As Set in Admin Template Parameters */
body.site {
border-top: 3px solid <?php echo $this->params->get('templateColor');?>;
background-color: <?php echo $this->params->get('templateBackgroundColor');?>
}
<?php
}
?>
<?php
$googlefontcss = ob_get_contents();
ob_end_clean();
file_put_contents('templates/'.$template.'/css/googlefonts.css', $googlefontcss);
?>
Heres my problem, all of these things are stored in a helper file which is called from my index file, but this has the effect that the CSS file is created every time that the page is loaded rather than when I adjust and save my params in the backend. Surely, if I got a lot of traffic, this is going to stress the server even though the css file is quite short (its longer than shown here).
Being a newbie, I have no idea how I would avoid this problem and instead only have the file written when the options are changed and saved. Anybody suggest a better way?
I'm really confused about why you would do this at all. First, Joomla has a way to save parameters for a template and to use them, which you are doing. It also has a standard way to include a css file in your template. You can do this easily with a plugin if you don't want to addStyle() directly to the the template file. Also for google font api just look at how protostar does it.
I really think you need to look at how templates work in Joomla --- it's not modifying the core to modify your template index unless you are using one of the included templates --- in which case copy it, which you can do with one click in 2.5 and 3.
If you really absolutely have to do this, make a plugin. There are a lot of examples in the JED of plugins to include a file in a template. http://extensions.joomla.org/extensions/core-enhancements/coding-a-scripts-integration/head-code

Access background image in Wordpress

I'm currently turning a HTML page into a WordPress theme. Throughout the site I have a series of divs that use CSS backgrounds. What is the best practice for linking those images, so the user can change them as they please?
For reference, in the HTML, I have: background-image:url(/site/sprite.png);
You can use custom fields. If you don't know how to make them or you want an easy and robust way to manage them you can find the "Advanced Custom Fields" plugin in the wordpress.org plugin repository. It's free and it's very nice.
The way you would use custom fields here is because you will set those backgrounds with inline style to your theme. Otherwise "the user" will have to know how to change a CSS line of code (not very practical).
If you set them inline they would look something like this:
<div id="divBackground01" style="background: url(<?php echo get_post_meta('$post->ID','div-bg-01',true); ?>);>
</div>
Another option that I've seen people do is make the CSS file in a PHP file... you would use something like:
<style>
#divBackground01 {
background: url(<?php echo get_post_meta('$post->ID','div-bg-01',true); ?>);
}
</style>
Note that it's using PHP because the file would actually be a PHP file... otherwise you can't use PHP in a CSS file. Not sure that it's a very good practice to do this, but it's something doable as another option if you want.
Best to stick with adding the background style inline with the custom field. You can use PHP to make it conditional if needed and you can probably setup 1 post (so you have single ID) with all the custom fields... or whatever way you would prefer to present it to the user is your choice.

Enforcing CSS integrity over imported php pages

I'm trying to import a php file containing a HTML script with separate CSS and js files into another php file which contains my header and footer. The header and footer are from a template which uses a very messy and convoluted CSS which basically has rules for everything in almost 10 different locations/files. When I import my php into this main template page, all the imported page's styles also inherit from the base template which basically overrides my stuff. Is there a way to enforce each php/html script to maintain their own styles without having to inherit from one another while they're being imported from one file to another?
Many Thanks
How are you importing the files?
Is your answer is using include() or require() then the answer is no! When the html code is generated, all this will show it in the same page, that's what all the css and js files are applied to your html.
What you can do is add the css and js files to a file (eg: assets.php), establish an order and then import that into your main.php and resolve all the problems with the classes and ids on your html to avoid overriding.
EDIT: about CSS load order
The order in which you load your CSS files has very little influence in how styles are applied. What styles are applied to a certain element is determined by the specificity of the selectors used in the CSS rule. A higher specificity overrules a lower specificity, even if the style with the lower specificity is declared later.
CSS Specificity: Things You Should Know
Specifics on CSS Specificity
you need to name space both your css and javascript to protect them from being polluted by your header and footer.
there are many name-spacing patterns out there.. but let me suggest a few:
css: for every page you import.. you can run a jQuery script like this:
jQuery(document).ready(function() {
jQuery('body').attr('id','importedPagei');
}
then when you import the css.. you should create a build script that appends the attribute body#importedPagei to every css you are calling
ie this is a sample of the css of the importing page before running your build script:
.style1 {
color:red
}
and after running the jQuery script:
body#importedPagei .style1 {
color:red
}
so let's say that before.. your header template had the following class:
//header.css
h1 {
color: red;
}
and in your imported file you had
//importedFile.css
h1 {
color:blue;
}
then the final outcome in your old solution will have the template header style overriding yours:
//old final outcome
h1 {
color:blue;
}
but with the proposed solution above you will have (as mentioned before):
//importedFile.css
body#importedPagei h1 {
color: red;
}
and since you attached an id attribut to the body node of importedFile.html using jQuery, the html will look like this
<body id="importedFile">
..
<h1>hello world</h1>
..
</body>
so in this case.. using css cascading rules.. the css selector of your imported file is stronger than that of the template.. and so the final style applied will be color: red
javascript:
you can also use a build script to selectively import specific javascript files for specific pages..
another clean way is to use js.node modules.. the problem with javascript is that everything is in the global namespace.. there are some name spacing patterns that you can use.. but node.js provided a built in and very clean solution for it. and so you can have all the javascript in your final code but have node.js take care of compartmentalising it. it all depends on how much time you want to invest in solving this problem

Minimize code size to avoid duplication of the same code

I need one advice from you. I am working on a website, which uses PHP and HTML. As the biggest part of the header and footer code will be same for many pages, I am thinking of using PHP's include to avoid code duplication. But, each of those pages requires different stylesheets and JS files included. What do you think how could I let the other file know what scripts and stylesheet to import?
Our company does this:
The header reads the filename of the page calling it when it's included.
Then, it changes the extension to '.js' and outputs that if it exists. Same for CSS.
So if I have a page "register.php", it will auto-include "register.js" and "register.css" if they exist.
Here's what I do:
<?php include("includes/headContent.php"); ?>
<title>Page title goes here!</title>
<script src="script_only_used_on_this_page"></script>
<?php
require_once("includes/siteHeader.php");
?>
Site Content Goes Here!!
<?php
require_once("includes/siteFooter.php");
?>
Head Content includes any PHP I want included in every page, as well as the opening html and head tag, and any Javascript libraries and css stylesheets I want on every page. Site header closes the /head tag, and opens the body as well as printing out my site header and some other markup that goes on every page. Finally Site Footer closes out my template. Everything in between is my content area!
There are lots of different ways you can do templating, if you wanted to create a simple include and an echoHeader() and an echoFooter() function... just have the echoHeader function accept a parameter which you would pass your javascript and CSS lines to.
you can use MVC coding pattern

Categories