I want to add a style tag to the head section according to shortcode parameters. I wrote a function for styles and want to call its add_action
in a shortcode function.
However, the style is not added in the head. If I call add_action outside of the function, it works successfully.
Please let me know how I can call the statement “add_action” inside a php function, and how I can send parameters to a function to call add_action.
This is my code:
function ag_appearance( $year ){
?>
<style type="text/css">
/*Some style here*/
</style>
<?php
}
add_action( 'wp_head', 'ag_appearance' ); /* this is working */
function dp_agenda( $atts, $content = null ){
extract( shortcode_atts( array(
'year' => '',
'day' => '',
'summit' => '',
'complexity' => '',
'certification' => '',
'event' => '',
'make' => ''
), $atts ) );
add_action( 'wp_head', 'ag_appearance' );
/* this is not working, while i want to call here by $year parameter */
}
I would suggest creating a CSS file containing the style you want to add to the header (
appearance.css
for example) and placing that in the theme folder so you know where it is (I usually use/css
for styles). Then use wp_enqueue_style to set the style in the header when the containing function is called. Sort of like this:Enqueued styles in WordPress, by default, are placed in the head via
wp_head()
and scripts are placed wherever you havewp_footer()
placed, usually before the</body>
tag.You can also use wp_enqueue_script to pull your javascript files.