'How do I pass the dynamic output of a php variable or php function to a CSS variable?
The WordPress plugin PolyLang provides translations to a chosen language. Its functionality of "Strings translations" consists of a list of strings with custom translations. Every one of these strings is a php function that, once loaded in a web browser, displays a different html string based on the browser's language.
In php:
<?php pll_e('Startpage'); ?>
Becomes in browser: Startpage / Word in another language.
I would like to use these html strings in the right language in my CSS print stylesheet, so that I can add them with "content: ... ;" to my printed page.
The problem is that I can't seem to "send" the output of the php function to my CSS stylesheet without a complicated workaround using JavaScript.
I have already tried Right-way-for-pass-variable-php-to-css-in-wordpress, but including a CSS stylesheet with PHP code as style.php does not work.
Is there another way to do this?
Solution 1:[1]
Here is a working solution:
Put the php code that produces the html string into a php file of the page that is always loaded (e. g. the header.php). Assign an ID.
<div id="myid"><?php produces-a-string() ?></div>
Make the html string invisible to the ordinary user with CSS:
#myid {
display: none;
}
Grab the loaded html string with JavaScript to create a CSS variable:
document.onload = function() {
var grab = document.getElementById("myid");
var strText = grab.innerText;
grab.setProperty("--grabbed", strText);
}
The html must be loaded before JavaScript, else the corresponding JavaScript variable will be null. Hence put the JavaScript in an event listener "load".
This adds to the CSS code:
#myid {
display: none;
--grabbed: string-produced;
}
The string can then be used by other CSS attributes:
main {
attribute: var(--grabbed);
}
which acts like:
main {
attribute: string-produced;
}
If you want to use the produced string with CSS attribute "content", creating a CSS variable does not work, as content does not accept var() as value.
But content accepts attr() as value. This accesses the HTML global attributes (allowed for any HTML element). I chose the attribute "title".
In JavaScript, you have to assign the global attribute to the element with the class or id to which you want to add a "content" attribute.
document.onload = function() {
var grab = document.getElementById("myid");
var strText = grab.innerText;
document.getElementBy[id-where-content-is-added].setAttribute("title", strText);
}
This makes the following possible:
#id-where-content-is-added {
content: attr(title);
}
which acts like:
#id-where-content-is-added {
content: string-produced;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |