4

As I told in an earlier question is have a theme with hundreds of mods, which I gather in one mod so I don't have to loop through all mods at every pageload.

Now, the codex has you dump customizer styles directly in the head, which isn't very elegant. There is wp_add_inline_style to add css in an orderly way to an existing style sheet. This looks like this and it works fine:

$style = get_theme_mod ('all-mods');
wp_add_inline_style ('my-main-style',$style);

There's one problem, however. If I build a child theme, the inline styles are still added directly after the parent styles. This causes them to be overruled by the child theme css, which is loaded after the parent's to make sure it overrides those styles. This is not what the user expects.

The customizer styles should have the highest priority, so in some way I must make sure they are the last ones to be loaded in the head. I can detect if there's a child theme active, but cannot know the handle of the child style to add the inline styles to it.

At this moment I have simply defined an empty css file, which I enqueue right at the end of the head, and then add the inline styles. But this is far from elegant, which is why I took this path in the first place. Does anybody know of a smarter approach?

1
  • 1
    Personally I don't see the problem with the codex's suggestion - just use a very late hook on wp_head and output a <style> tag. Ultimately, this is what you want - to ensure the customizer styles take priority over everything else. Nov 12, 2016 at 13:32

1 Answer 1

1

You can try to detect if the current used theme is a child and if so pointing the inline CSS to the right style. I didn't tested this solution but could be a good starting point.

function mytheme_enqueue_style()
{
    wp_enqueue_style( 'parent-theme-style',get_template_directory_uri() . '/style.css', false );

    if(is_child_theme())
    {
        wp_enqueue_style( 'child-theme-style', get_stylesheet_directory_uri() . '/style.css', array('parent-theme-style')  );
    }

    $style = get_theme_mod ('all-mods');
    $where = is_child_theme() ? 'child-theme-style' : 'parent-theme-style';
    wp_add_inline_style( $where, $style );
}

add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_style' );

NOTE

There is a difference between get_template_directory_uri() and get_stylesheet_directory_uri() in fact on codex we have

In the event a child theme is being used, this function will return the child's theme directory URI. Use get_template_directory_uri() to avoid being overridden by a child theme.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.