WordPress add_action inside another function

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.

Read More

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 */
}

Related posts

Leave a Reply

1 comment

  1. 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:

    function dp_agenda( $atts, $content = null ){
       extract( shortcode_atts( array(
        'year' => '',
        'day' => '',
        'summit' => '',
        'complexity' => '',
        'certification' => '',
        'event' => '',
        'make' => ''
        ), $atts ) );
        wp_enqueue_style('appearance',get_stylesheet_directory_uri().'/css/appearance.css'); 
      /*  this is not working, while i want to call here by $year parameter */
    }
    

    Enqueued styles in WordPress, by default, are placed in the head via wp_head() and scripts are placed wherever you have wp_footer() placed, usually before the </body> tag.

    You can also use wp_enqueue_script to pull your javascript files.