Enqueue styles and scripts for WordPress Gutenberg block - wordpress-theming

what are the best or the recommended way to Enqueue styles and scripts for WordPress Gutenberg block ?
i see some developers recommend enqueue_block_assets hook and others recommend init hook with refering to styles and scripts handles in register_block_type php function
What should i use ?

It does depends on the use case as not all cases are the same but I believe and stand to be corrected, Wordpress now recommends using register_block_type to add scripts and css instead.
This is because adding it via block registration allows Wordpress to add the css only when a block is used.
Test it and see. Add block assets using enqueue_block_assets and it will load on every page even if the block is not loaded on the page.
The styles and scripts added below will only be added when the block is added to a page.
My answer is based on some of my own testing recently. CSS Added via blocks using the register block are injected when a block is added not at load time like with enqueue_block_assets
Also see this article as a reference in terms of it now being recommended by Wordpress
register_block_type('namespace/your-block', array(
'style' => 'view-style-handle',
'editor_style' => 'editor-style-handle',
'editor_script' => 'block-script-handle'
));

Related

How do I add inline CSS into the Wordpress Visual Composer?

I might be asking the wrong question (I'm not a coder), but I'm attempting to paste HTML and the inline stylesheet into the text-side (HTML-side) of the Wordpress Visual Composer to create an email layout, and the finished product of that is the entire stylesheet written out above the un-styled HTML layout, so I'm assuming inline stylesheets are not supported in this composer.
Some back story for clarity, I'm using the plugin 'Download After Email' which only provides the standard Wordpress visual composer in order to create the email a user receives once they 'sign up'. This seemingly limits me to either jazzing up some text a little bit like I was using Microsoft Word (which isn't sufficient for a brand-focused business), or using raw standalone HTML, which isn't really sufficient for a properly formatted template.
Are there any plugins which may assist in adding CSS styling here that will work once it's displayed externally to the website, i.e. in an email browser?
Judging by the image, you have a regular editor but not Visual Composer, and this is very good because this is the only right direction! You cannot create email templates using the constructor (Visual Composer) since creating an email template requires special old school knowledge (Tables, inline styles) and clean markup. I advise you to take a ready-made template and change it to your own.
Example: https://colorlib.com/etc/email-template/3/index.html
What you need to know:
You need to use html tables
You need to use inline css
Use full src to display images (https://yoursite.wp/.../demo.jpg) the link you can get from the media post
Not recommended:
To use css styles in the header if you are interested in Gmail App support:
https://templates.mailchimp.com/resources/email-client-css-support/
Custom fonts
Visual Composer and any other constructor
Addition:
If you can use the shortcode system I recommend creating a mini plugin for you:
plugins/my-custom-emails [Root directory of new plugin]
plugins/my-custom-emails/my-custom-emails.php [Main php file of plugin]
plugins/my-custom-emails/emails/ [Directory for for all your templates]
plugins/my-custom-emails/emails/template1.html [First demo template]
my-custom-emails.php
<?php
/*
Plugin Name: My emails
Description: My custom emails
Version: 0.1.0
*/
define('MYCELS_DIR', plugin_dir_path(__FILE__));
add_shortcode( 'myemails', 'MYCELS_SHORTCODE' );
function MYCELS_SHORTCODE($attrs) {
if(empty($attrs['id'])) {
return 'ID required';
}
$ID = $attrs['id'];
$PATH = MYCELS_DIR . 'emails/'.$ID.'.html';
if(file_exists($PATH)) {
return file_get_contents($PATH);
} else {
return 'File with '. $ID . ' ID not exists';
}
}
template1.html
<div>
Template
</div>
And using:
[myemails id=template1]
Id = template name
If you want something very customisable this plug-in would work,
https://en-gb.wordpress.org/plugins/wp-html-mail/
It’s very good and would recommend!
With this you have full control over CSS and the HTML also comes with templates and has so much more control for what you need!

Yii2 add google font to head

I was wondering how do you add link tag/google font to head in yii2.
I want to add the following
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
I have found this documentation but doesn't mention anything about link/adding google font etc
The correct answer is to create a new AssetBundle.
While you can directly place the HTML for the fonts into the of your main.php file, this isn't the Yii way. If you have tried to load jQuery files this way, you might notice odd behavior when directly putting them into the HTML.
For example: Directly place the HTML tag for Bootstrap CDN into the head of your main.php. Then, somewhere in your code try to use the tooltip. You will get an error in your console that tooltip is not a function. - This is because the way Yii puts all your template files together, and at that time, Bootstrap is not available.
While simply loading a font probably won't cause any problems, it is a good idea to do things the way they were intended. Following MVC rules, properly documenting your code, and following the Yii best practices, will go a long way. Not only will you thank yourself a year later when you have to go back into a project, but the next guy will appreciate it. I can't stand going into systems, and seeing stuff thrown everywhere, chincy hacks, and spaghetti code, and no documentation or comments.
Correct Way:
Create a new AssetBundle. In your assets folder, you probably already have AppAsset.php. Duplicate it, and name it FontAsset.php.
Here is an example from my project, using 3 Google fonts.
FontAsset.php
<?php
namespace app\assets;
use yii\web\AssetBundle;
class FontAsset extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'//fonts.googleapis.com/css?family=Open+Sans:400,700',
'//fonts.googleapis.com/css?family=Ubuntu:400,700',
'//fonts.googleapis.com/css?family=Oswald:400,700'
];
public $cssOptions = [
'type' => 'text/css',
];
}
In your layout, main.php for example. Right under where you see AppAsset::register($this)
main.php
use app\assets\FontAsset;
FontAsset::register($this);
For every layout file that you want to load those fonts, include the FontAsset.
The AssetBundle is basically a bundle of CSS and/or JS files and options. You could add another one for say JWPlayer say named VideoAsset, and add your JS/CSS files for JWPlayer in it.
Point being, you shouldn't be adding these things directly into the HTML of the layouts directly, as it can cause problems. Let the AssetManager handle them by declaring AssetBundles.
It might save you later down the road!
The best way is to create an asset bundle and add the link to the bundle.
You can find a complete guide here:
http://www.yiiframework.com/doc-2.0/guide-structure-assets.html
You can put it directly in the head of the layout (file views/layouts/main.php)

wp_enqueue_style Does Not Behave As Documented

I have the following written in a driver:
add_action( 'wp_enqueue_scripts', 'add_css_file' );
function add_css_file()
{
// Tried this prior:
// $path = ABSPATH . "/wp-content/plugins/this_plugin/css/";
// wp_register_style( 'css_file', $path.'css_file.css' );
wp_register_style( 'css_file', 'http://subdomain.mysite.com/wp-content/plugins/this_plugin/css/css_file.css' );
wp_enqueue_style( 'css_file' );
}
The string "css_file" does not appear in the View Source HTML and the CSS rules defined therein do not take effect.
Have you included wp_head() in the <head> of your page? wp_head() will add your queued styles and scripts to the page.
The problem for me lay in the fact that I am modifying the Admin screen rather than the display of a Page or Post to viewers.
Replace:
wp_enqueue_script(...)
With:
admin_enqueue_script(...)
Best of luck.
I have just tried this snippet in my site, and it is working properly. You may get conflict with some other plugin/code.
Also make sure you don't have any Cache enabled, and if so, try to clean up the cache. Also try to clean out your browser cache.
Finally, if non of the above works for you, try to de-activate your plugins, one by one in order to see if some of the plugins conflicts with this function, and in last step try to change theme, also to make sure the current theme doesn't conflict with this function.

Using dependencies in wp_register_style() for wordpress

I am trying to get a custom css file to load after the plugin stylesheets. I was thinking I could use the $deps parameter of wp_register_style(), but the css file does not load at all when I add the array(). This happens no matter what is included in the $deps array(), ie (array('style')
, array('style.css')).
Is there an issue with the call, or a better way of doing this?
In my functions.php
// Load custom css
add_action('wp_enqueue_scripts', 'prefix_add_my_stylesheet');
function prefix_add_my_stylesheet() {
wp_register_style( 'custom-supersized-styles', get_template_directory_uri(). '/css/custom-supersized-styles.css', array('style','supersized');
wp_enqueue_style( 'custom-supersized-styles' );
}
If you're using the WP Supersized plugin try registering your function like so:
// Load custom css
add_action('wp_enqueue_scripts', 'prefix_add_my_stylesheet', 999);
The dependencies array (the parameter you're attempting to use to add supersized with) depends on supersized having already been registered by WordPress. If you set the priority of your own prefix_add_my_stylesheet to a higher number, it should then load after the plugin has registered and loaded its CSS (and thus will be available).
In addition, you can remove the style as a dependency. (style is never registered by WordPress as a dependency handler, and your enqueued scripts / css should be loading after style.css loads anyway).
Hope that helps!

Keeping the basic layout same across the web pages

I have a website in which I finished with the basic layout, design, fonts, styles, css etc.
For almost whole of the website, the layout i.e the sidebar, the footer, the background etc. will remain the same. There are custom embedded fonts used as well.
Since this basic layout will remain the same all across the website, I wanted to ask how can I prevent downloading of this content (like side-bar, fonts, or javascript etc.) again for the user, so that the other pages after the start do not take as much time as the start page.
I am sure there would be some mechanism since most of the websites have header/footer/sidebar in common across the pages. My website is in plain html/css, and there's no backend being used. Any ideas?
Your images, fonts, css and other contents will most likely be cached by the client's browser on the first hit, so it will be downloaded just once.
For the html page itself, since you use static html content, the only way I can think of is using AJAX request.
You probably want to use includes. So on each page you'd have a header include, a footer include, a sidebar include and even an include containing links to your css/js files.
Simplest way to do this would be to change your pages to be .php pages and use php includes to pull in the header file, footer file etc.
You can static-site generator like Jekyll.
You may design a basic layout first.
Avoid inline and embedded CSS maximum and add a class (can assign to multiple) or id (can assign to single) to common selectors.
Make a master stylesheet like master.css and attach this to every page.
Hope this helps.
You can do this in two way. You say you don't have a backend, however the server where your website is hosted can be the backend.
Without any backend interaction:
If you really prefer not to use the backend at all, you can make this a single page website, with some javascript to switch the content you have in there. The idea is you have your website structure, and your default data available the way you normally have it right. But you also have the html for your other pages in hidden divs. Then when you want to switch to say the about link you use javascript to get the content from the hidden div with that content and you place that content in the main div.
<!--First lets use jquery thought it can use some other framework-->
<script src="http://code.google.com/apis/ajaxlibs/documentation/index.html#jquery"></script>
<script>
$('a[href=#myAboutPage]').on('click',function(){//Whenever link that points to #myAboutPage is clicked
var getHTMLFROM = document.getElementById('myAboutPageHiddenContent').innerHTML;
//And place it on main div
document.getElementById('mainDivContent').innerHTML = getHTMLFROM
});
</script>
If you wanted to use some ajax interactions:
The process would be the same with the exception that the getHTMLFROM content, would actually be an html file that you request from the server.
Both of this javascript oriented methods will work, but would NOT recommend if you want your information to be SEO friendly. With that said reuse an external piece of css, to minimize redownloading the styling of your interface every single time.
There are definitely many ways to do this. I am a fan of dynamic inclusion. Here is a link to a great tutorial which explains how to set it up for your own page very simply. Dynamic Inclusion Tutorial NOTE: Don't be afaid of PHP, or having to change your file extension to PHP. It won't change your coding experience at all. It will just enhance your abilities.
I also have used the Javascript feature to hide certain elements. Depending on the size of your website, it may be just as easy to reload your CSS and navigation elements. However, if you really don't want your menu and logo to blink momentarily while it is reloading, you can just hide/reveal elements very simply with a bit of JS.
Here is an example function from my website:
function toggleVisible(e){
var i = e.id;
if(e.className == 'collapsed')
{
e.className = 'expanded';
e.innerHTML = 'Hide'
var hiddenArray = document.getElementsByClassName('hidden' + i);
hiddenArray[0].setAttribute('class', 'expanded' + i);
}
else if (e.className == 'expanded')
{
e.className = 'collapsed';
e.innerHTML = 'Show More';
var expandedArray = document.getElementsByClassName('expanded' + i);
expandedArray[0].setAttribute('class', 'hidden' + i);
}
}
The above code will run when the following link is clicked:
ANYWEBSITE.com || <a onClick="toggleVisible(this)" id="4" class="collapsed">Show More</a> || View PDF
Also, another user mentioned caching. Caching appears to be unreliable. Check out the following links for more info:
AJAX cache
HTML5 Application cache
2009 article about browser caching from stackoverflow.com question