I'm new to wordpress and I'm trying to get this to work by following the wordpress codex but I feel like I must be missing something obvious.

I have a child theme based off of a parent one, and I created a file called "functions.php" in the root directory of the child theme with FTP. I added this code to it:

function my_canvas_include(){
  wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/css/stylesheet.css');
  wp_enqueue_script( 'script-name', get_stylesheet_directory_uri() . '/js/site.js', array('jquery'), '1.0.0', true );

  $output = '';
  $output .= '<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas ';
  return $output;

add_shortcode('my_canvas', 'my_canvas_include');

The example here has some contrived names for the function and shortcode. The idea, though, is that I want to include the js and stylesheet only on those pages I need it (by using the shortcode [my_canvas] when editing a page in wordpress admin) which will also output that canvas element (the styles and js will manipulate the canvas element).

Using the shortcode...mostly works. It adds the canvas element, but I don't see the stylesheet or js file anywhere in the source, and even when i put alert('hi') in the js file it doesn't do anything when I use the shortcode on the page.

What am I doing wrong here? Is there another way I'm supposed to conditionally include stylesheets or scripts on only pages that need them?

  • Your shortcode works when I test it. The stylesheet and script loads.
    – s_ha_dum
    Sep 11, 2013 at 17:39
  • Ok one question, (I've read up some more), is it loading them both into wp_footer()? That's... not a good idea for stylesheets is it?
    – nzifnab
    Sep 11, 2013 at 17:41
  • It isn't correct for stylesheets but as you are loading after the <head> has printed, you have no choice unless you want to do something like this: wordpress.stackexchange.com/a/101515/21376
    – s_ha_dum
    Sep 11, 2013 at 17:45


Your Answer

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