Global Variables to store all CSS from Wordpress Shortcodes - php

I need your input and insight on using GLOBALS variable to store all CSS that is generated through Wordpress Shortcodes. I have designed Shortcode that use the following css format:
<style>
#divID1 .blah { /* code */}
#divID2 .blah { /* code */}
</style>
this works well, however while validating through https://validator.w3.org I keep getting errors like below:
- Element style is missing required attribute scoped.
or sometimes..
- Element style not allowed as child of element div in this context. (Suppressing further errors from this subtree.)
Now my question is what if I keep adding that dynamic CSS code to one variable $GLOBALS['custom-css'] .= 'whatever code';
and I can print that variable within <head>. Is this insecure ? OR the $GLOBALS doesn't work on many hosts ? Or it may effect Wordpress site, I don't want to risk and ending up it not working on many different web hosts.
Can someone please explain and/or confirm if that is a right method.

Related

Add Dynamic PHP Code in WordPress Via jQuery HTML Replace?

I'm stuck using a theme in WordPress for a client where the header is horrible in responsive view. I can work with desktop widths but anything below 768px needs to have an entirely different markup because of the clients demands -- any attempt to try to do this via CSS has led to even more UI disasters. My hope was to utilize jQuery's .html() functionality to swap out Bootstrap grid elements at < 768px. Here's a snippet example -- say I needed to move the logo from a far right position in desktop to the first element on the left in a header. I'm using the theme's declarations for the dynamic logo correctly:
if($(window).width() < 768) {
$('.top-bar').html('<div class="col-md-3"><?php vg_ebuilder_display_logo_sticky(); ?><div class="logo-inside"><?php vg_ebuilder_display_top_logo(); ?></div></div>');
}
But this returns commented out PHP:
<!--?php vg_ebuilder_display_logo_sticky(); ?-->
and
<!--?php vg_ebuilder_display_top_logo(); ?-->
So, maybe two questions here: is there a way to add dynamic PHP like this in WordPress via a jQuery .html() function on $(document).ready and, assuming it could, would it indeed be dynamic if loaded after the DOM?
No. PHP runs on the server, not the client. The javascript would need to make a call to an endpoint that would perform the php logic, return a response, and that response put on the page. Inserting php on the client will not be invoked.
I can't 'comment' a suggestion to you as my reputation isn't yet 50, so hopefully this is the right answer. I found this worked for me with a similar issue in Joomla (Q48891999).
In the div you want to change, add a unique class, e.g. "builder".
Then, if you need to, write a new css class or classes starting with
#media (max-width: 767px) {
.your_new_class {
}
}
- but not using the name 'builder' for the new class - in your custom css file for the div you want to change.
Then use jquery .addClass to apply the css class to your div in your index.php. Something like this:
<script>
$( ".builder" ).addClass( "the_class_you_want_to_apply another_class" );
</script>
The spaces between the parentheses and the double quotes are deliberate, as used in the examples on the jquery website.
In my case, I added this to the bottom of my index.php just before the closing body tag.
You may need to have more than one of these scripts to apply to different elements.

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

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

Define php variables that contain both HTML and subsequently, dynamically settable variables for use later in script?

I'm wondering if I want to do may not be possible... My PHP code loops through jpgs and flv files in an image directory and generates content that consists of in some instances HTML, in others CSS combined with dynamically determined values, for example:
'ul.set li.'.$className.
'{background: url(imagessmall/'.$fileName.')
left -2px no-repeat;}'
Since the above (and much longer sections of HTML+variables) occurs more than once in the code, and because it would make the code easier to review and maintain, I'd like to be able to separate out these html + $variable by defining a set of variables up front, then reference them as needed, for example:
$SDImagePreview =
'ul.set li.'.$className.
'{background: url(imagessmall/'.$fileName.')
left -2px no-repeat;}'
.
.
.
//Code that dynamically sets $className and $fileName is here
$write = fwrite($fileCSS, $SDImagePreview);
I've read on stackoverflow and elsewhere about using &, as in &$fieldName to pass values by reference, but haven't found examples of defining a variable that has within it a variable whose value can be set dynamically.
Am I trying to do something that is just not doable? Or are there alternate suggestions re: implementing the general approach I'm describing? Thanks for any suggestions.
Rather than embedding the html in the code itself, I'd like to be able to define a set of variables at the start of the code, then reference them as needed,
Yes its possible you just have to put your CSS directly to your code in the just add :
<style type="text/css" media="screen">
(...) you generate CSS
<?php print $SDImagePreview; ?>
</style>
CSS are most faster to load if is an extarnal .css file for the caching but in your case the CSS need to be generated in PHP so no cache can be done. If you want to have this change the CSS rule already define by other .css file juste put it after.

Filtering user input as CSS

I'm providing a way for my users to change the CSS of their user pages by entering some CSS in their settings page. Here is the HTML:
<textarea class="code" name="Settings[css]"></textarea>
In the controller:
$model = new Profile;
$model->css = $_POST['Settings']['css'];
I currently don't validate the input for the CSS field. I was wondering if I could filter the CSS so that they couldn't put harmful code in to the page. For example, they could do:
</style>
Now I can put bad code in to your page
I don't think purifying css with HTMLpurifier would be appropriate because CSS usually contains special characters, but correct me if I'm wrong.
Thanks
This has nothing to do with Yii in any shape of form.
The "invalid code" that you provided in example could be easily removed, if you include the User CSS as an external file.
And that is not all they can do with CSS. You should manually remove following entries:
line containing behavior: url( .. )
all instances where !important is used
entries which contain selectors to specific ID, like #ads and #logo
strip_tags() can remove html tags from the input, though I don't think it's the only thing you have to worry about.
An easier solution may be to load this style through an external stylesheet (<link rel="stylesheet" type="text/css" href="userstyle.php?uid=1235" />) instead of an inline style block, that way there's no way to break out.
You could try a php css parser like this:
https://github.com/sabberworm/PHP-CSS-Parser
But I can't tell you anything about the quality of code it produces or how it handles problems with input.
What I do know is that LESS has good debugging usually.
If you use the LESS php class you could build a system where the $_POST['Settings']['css'] is used to create valid CSS. Or if errors occur you can catch them and return that to the browser.
Yes this effectively enables you to use LESS syntax in the field but I don't see the harm in that. LESS is in some ways stricter in the syntax of CSS through, requiring semicolons regardless of if its the last property in the list and extra characters can also trigger errors.
The debugging information for the javascript version is pretty solid though, I can't personally vouch for the PHP class since I only use the JS, but from what I hear its the second best thing after the JS.
http://leafo.net/lessphp/
http://lesscss.org/

Specifying a php include to use a certain stylesheet?

I am dividing my website in the typical php include way. If I want the includes to use their own stylesheet how is this done? For example if I have include "header.php", how can I make it so that a stylesheet only applies to this include?
You can do this either by including a different stylesheet to begin with, or by giving your <body> element an id or class attribute that enables you to write selectors such as
body#header {
/* ... */
}
The first approach plugs in at the <head> tag render code, the second does so at the <body> tag render code. You need to write your code such that one of these places also knows which PHP script you intend to include (or have already included).
you cannot bind css to a php-include. you respond to a browser with HTML-code. with php you may control which css(-file) will be included in the HTML finally. you may bind css to certain tags, or classes, or ids. but those are HTML-concepts and have no relation to PHP except for the fact that PHP will control the final HTML-code.

Categories