I just started to use WordPress to start building a website, but as I need to use the get_header()
function to retrieve the <head>
content and I have a very large project, I wanted to put a CSS file depending on the page that is being displayed. After a few tries I came up with a solution, but I think that I can do it in a better way and I need your help to optimize it.
I'd like my code to be \$O(1)\$ not \$O(n)\$.
Here is my PHP snippet that goes into the functions.php file:
function website_files_per_page() {
$pagelist = get_pages();
$index = sizeof($pagelist);
while ($index --) {
$pagename = $pagelist[$index]->post_name;
if (is_page($pagename)){
$styleName = "website_".$pagename."_styles";
$styleDir = get_theme_file_uri("/style/".$pagename.".css");
wp_enqueue_style($styleName, $styleDir);
break;
}
}
}
add_action("wp_print_styles", "website_files_per_page");
1 Answer 1
A simpler approach to add the style can be used
Per your request:
I'd like my code to be \$O(1)\$ not \$O(n)\$.
I haven’t tested this but based on this SO answer using global $post
and $post->page_title
to set $pagename
should allow for elimination for the while
loop.
function website_files_per_page() {
global $post;
$pagename = $post->post_title;
if (!$pagename) {
return; //no page name
}
$styleName = "website_".$pagename."_styles";
$styleDir = get_theme_file_uri("/style/".$pagename.".css");
wp_enqueue_style($styleName, $styleDir);
}
add_action("wp_print_styles", "website_files_per_page");
That would allow the code to run in \$O(1)\$ time instead of \$O(n)\$.
PHP can parse variables in double quoted strings
Per the PHP documentation for Strings:
Simple syntax
If a dollar sign (
$
) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.
Thus a line like this:
$styleName = "website_".$pagename."_styles";
Can be simplified to:
$styleName = "website_{$pagename}_styles";
PHP can handle the iteration
If the suggestion to use $post
doesn’t work, you may be able to change the while
loop to a foreach
. foreach
provides an easy way to iterate over arrays:
foreach ($pagelist as $post) {
$pagename = $post->post_name;
if (is_page($pagename)) {
...
With this approach there is no need to initialize and update a counter (e.g. $index
) to dereference elements in the array.
If there was a need to access the index/counter variable then the second syntax can be used for that:
foreach ($pagelist as $index => $post) {
-
\$\begingroup\$ This works pretty awesome and does what I wanted, reduce the time to O(1). Thanks! \$\endgroup\$maneroto– maneroto2021年01月08日 23:11:13 +00:00Commented Jan 8, 2021 at 23:11
Explore related questions
See similar questions with these tags.