Adding preload to css files in WordPress - wordpress

I am new to WordPress and am trying to preload certain css files. I understand that they are loaded into the head using wp_enqueue_style(), so I am trying to access the html generated from that to add rel="preload".
So far it looks like this
wp_enqueue_script('main-style', 'styles/main-style.css', false, null);
add_filter('script_loader_tag', 'preload_filter', 10, 2);
function preload_filter($html, $handle) {
if (strcmp($handle, 'main-style') == 0) {
$html = str_replace("rel='stylesheet'", "rel='preload' as='style' ", $html);
}
return $html;
}
Although when I add this preload_filter function my css fails to load completely, and not just for the specified stylesheet... Am I missing anything in trying to do this, or is there a simpler method? Any help would be greatly appreciated.

To enqueue style file, you need to use wp_enqueue_style function. You used wp_enqueue_script which is used to enqueue JavaScript file.
wp_enqueue_style('preload-style', 'styles/main-style.css', false, null);
And you need to use style_loader_tag filter to filter the HTML link tag of an enqueued style.
add_filter( 'style_loader_tag', 'preload_filter', 10, 2 );
function preload_filter( $html, $handle ){
if (strcmp($handle, 'preload-style') == 0) {
$html = str_replace("rel='stylesheet'", "rel='preload' as='style' ", $html);
}
return $html;
}
But you used script_loader_tag filter which is used to filter <script> tag.

(Can't reply, but extends this answer https://stackoverflow.com/a/66640766/1898675)
This modification use the noscript fallback, which is recommended by google for defer css. https://web.dev/defer-non-critical-css/#optimize
add_filter( 'style_loader_tag', 'preload_filter', 10, 2 );
function preload_filter( $html, $handle ){
if (strcmp($handle, 'preload-style') == 0) {
$fallback = '<noscript>' . $html . '</noscript>';
$preload = str_replace("rel='stylesheet'", "rel='preload' as='style' onload='this.rel=\"stylesheet\"'", $html);
$html = $preload . $fallback;
}
return $html;
}

Related

How to get post id using add_my_endpoint?

I'm creating AMP pages on my own, without a plugin, and I have one problem that I can't solve.
function h34_endpoints_add_endpoint_pinup()
{
add_rewrite_endpoint('amp', EP_ALL);
}
add_action('init', 'h34_endpoints_add_endpoint_pinup');
add_filter('template_include', 'amp_page_template_pinup', 2);
function amp_page_template_pinup($template)
{
if (get_query_var('amp', false) !== false) {
$template = plugin_dir_path(__FILE__) . 'amp-template.php';
}
return $template;
}
Now in the amp-template.php file ш need to get the post data (if it is a post) but where and how to get the post ID?
global $post; shows nothing
get_the_ID() - doesn't output anything either.
I will be grateful for any help

Wordpress: add custom params to all URLS

I have an addition to url e.g. /products/myproduct/?v=iphone-x/transparent/*/Green
So what I need is for wordpress to add the ?v=iphone-x/transparent/*/Green to all links on the page (only '<a href="">'s, no 'img src=""' or others)
I have managed to do that, but it's a little "dirty". Is there any neat function to add the parameter to all links?
The code I have is as follows:
function callback($buffer) {
// modify buffer here, and then return the updated code
$temp = explode('href="', $buffer);
$buffer = $temp[0];
array_shift($temp);
foreach($temp as $t){
$tt = explode('"', $t, 2);
$buffer .= 'href="'.$tt[0].'?v='.$_GET['v'].'"'.$tt[1];
}
return $buffer;
}
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }
add_action('wp_head', 'buffer_start');
add_action('wp_footer', 'buffer_end');
One way you can achieve this is to hook into "the_content" filter. By using regexp with preg_replace_callback function you can get decent results.
function add_para( $content ) {
$content = preg_replace_callback(
"/href=(?>'|\")([^\"']+)(?>'|\")/",
function($m) {
print_r($m);
return "href='".$m[1]."/additional-param'";
},
$content);
return $content;
}
add_filter( 'the_content', 'add_para', 0 );
However, you might run into some issues particularly if your content is not formatted probably (extra spaces, missing tags .. etc).
So the alternative is either to us a JS approach (jQuery for example), or using PHP DOM parser like: PHP Simple HTML DOM Parser

Why won't WordPress load thickbox and media-upload scripts?

I'm working on a plugin that uses thickbox and media-upload to set some images. Neither will load using this code:
function add_my_files() {
echo 'happy happy happy';
wp_register_style( 'adminstyles', plugins_url('/css/slider.css', __FILE__));
wp_enqueue_style( 'adminstyles' );
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('hdjs',plugins_url('/js/slider.js', __FILE__),array('media-upload','thickbox'),'',true);
wp_enqueue_script('hdjs');
}
add_action( 'admin_init', 'add_my_files' );
my css and js files load but not thickbox and media-upload.
Thanks
The correct hook to include your asset files in WP is admin_enqueue_scripts:
NOTE: I recommend you too use get_current_screen (see is_my_admin_screen() definition below) to just include your js/css files when you actually needed.
add_action('admin_enqueue_scripts', 'add_my_files');
function add_my_files()
{
/*
* a good WP citizen only loads
* their javascript/css where it is needed
*/
if ( ! is_my_admin_screen()) // defined below
return;
wp_register_style('adminstyles', plugins_url('/css/slider.css', __FILE__));
wp_enqueue_style('adminstyles');
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('hdjs', plugins_url('/js/slider.js', __FILE__), array('media-upload', 'thickbox'), '', true);
wp_enqueue_script('hdjs');
}
function is_my_admin_screen()
{
$screen = get_current_screen();
if (is_object($screen) && $screen->id == 'my_plugin_page_id') // var_dump($screen->id); find your own id
return true;
else
return false;
}
ref: http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts
ref: http://codex.wordpress.org/Function_Reference/get_current_screen
Besides hopefully you are using a class to wrap all your plugin or you will have worse problems than this.
Please feedback. I am very interested in this issue because WP plugins puts food and beers on my table.

Wordpress - Apply remove_filter only on one page

I am inserting multiple pages in one page (with showmultiplepages plugin), and one page includes a php file (with exec-php).
I want to disable a filter only for this included page. If I add
remove_filter( 'the_content', 'wpautop' );
to my included page, any page comming after this page won't have filters too.
Is there some tag like 'the_page' so that only the page will have no filter?
Thanks for help.
I know this is an old question, but I thought I'd chime in for anyone looking to do this in a more general sense (e.g. not in conjunction with plugin output) and say that you could also just add this to your functions.php file:
add_filter('the_content', 'specific_no_wpautop', 9);
function specific_no_wpautop($content) {
if (is_page('YOUR PAGE')) { // or whatever other condition you like
remove_filter( 'the_content', 'wpautop' );
return $content;
} else {
return $content;
}
}
I suggest creating a page template for the "one page includes a php file (with exec-php)". Then add an if statement around the remove_filter(...) statement.
if (!is_page_template('my-page.php'))
remove_filter('the_content', 'wpautop');
Hope it works. ;P
Like mroncetwice, I too realize that this is an old question; however, I came to this thread looking for an answer when I saw his. I decided to improve upon it (in terms of suiting my own situation) and am sharing the results with the hope that it may also help others.
Turn wpautop on or off by default and list any exceptions:
/**
* Allow or remove wpautop based on criteria
*/
function conditional_wpautop($content) {
// true = wpautop is ON unless any exceptions are met
// false = wpautop is OFF unless any exceptions are met
$wpautop_on_by_default = true;
// List exceptions here (each exception should either return true or false)
$exceptions = array(
is_page_template('page-example-template.php'),
is_page('example-page'),
);
// Checks to see if any exceptions are met // Returns true or false
$exception_is_met = in_array(true, $exceptions);
// Returns the content
if ($wpautop_on_by_default==$exception_is_met) {
remove_filter('the_content','wpautop');
return $content;
} else {
return $content;
}
}
add_filter('the_content', 'conditional_wpautop', 9);
Does not work?
add_filter('the_content', 'specific_no_wpautop', 9);
function specific_no_wpautop($content) {
global $post;
if (is_single('5136') || ('3820')){ // or whatever other condition you like
remove_filter( 'the_content', 'wpautop' );
return $content;
} else {
return $content;
}
}

Wordpress: How to obtain different excerpt lengths depending on a parameter

The length of the excerpt in wordpress is 55 words by default.
I can modify this value with the following code:
function new_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');
So, the following call will return just 20 words:
the_excerpt();
But I can't figure out how could I add a parameter to obtain different lengths, so that I could call, for example:
the_excerpt(20);
the_excerpt(34);
Any ideas? Thanks!
uhm, answering me again, the solution was actually quite trivial. it's not possible, as far as i know, to pass a parameter to the function my_excerpt_length() (unless you want to modify the core code of wordpress), but it is possible to use a global variable. so, you can add something like this to your functions.php file:
function my_excerpt_length() {
global $myExcerptLength;
if ($myExcerptLength) {
return $myExcerptLength;
} else {
return 80; //default value
}
}
add_filter('excerpt_length', 'my_excerpt_length');
And then, before calling the excerpt within the loop, you specify a value for $myExcerptLength (don't forget to set it back to 0 if you want to have the default value for the rest of your posts):
<?php
$myExcerptLength=35;
echo get_the_excerpt();
$myExcerptLength=0;
?>
There is no way to do this as far as I have found using the_excerpt().
There is a similar StackOverflow question here.
The only thing I have found to do is write a new function to take the_excerpt()'s place. Put some variation of the code below into functions.php and call limit_content($yourLength) instead of the_excerpt().
function limit_content($content_length = 250, $allowtags = true, $allowedtags = '') {
global $post;
$content = $post->post_content;
$content = apply_filters('the_content', $content);
if (!$allowtags){
$allowedtags .= '<style>';
$content = strip_tags($content, $allowedtags);
}
$wordarray = explode(' ', $content, $content_length + 1);
if(count($wordarray) > $content_length) {
array_pop($wordarray);
array_push($wordarray, '...');
$content = implode(' ', $wordarray);
$content .= "</p>";
}
echo $content;
}
(Function credit: fusedthought.com)
There are also "advanced excerpt" plugins that provide functionality like this you can check into.
Thanks for your answer, thaddeusmt.
I am finally implementing the following solution, which offers a different length depending on the category and a counter ($myCounter is a counter within the loop)
/* Custom length for the_excerpt */
function my_excerpt_length($length) {
global $myCounter;
if (is_home()) {
return 80;
} else if(is_archive()) {
if ($myCounter==1) {
return 60;
} else {
return 25;
}
} else {
return 80;
}
}
add_filter('excerpt_length', 'my_excerpt_length');

Resources