Forums

[resolved] Loading javascript on chosen page ( conditionally ) (8 posts)

  1. AxelYa
    Member
    Posted 2 years ago #

    I am trying to load google map on a page and I created a function loading scripts in my function php. It loads the map and OK, but I want to limit this function being loaded to a certian page.

    Conditional tags do not work for me here or I don't use them properly

    here is the code from function file

    function my_map() {
    if (!is_admin()) {
    wp_deregister_script('g_map');
    wp_register_script('g_map', 'http://maps.google.com/maps/api/js?sensor=false', false, '', true);
    wp_enqueue_script('g_map');
    
    wp_enqueue_script('y_map', get_bloginfo('template_url') . '/js/ymap.js', array('g_map'), '1.0', true);
    }
    }
    add_action('init', 'my_map');

    Please show me the way to do it

  2. racer x
    Member
    Posted 2 years ago #

    <?php if (is_page('42')) {
         my_map();
    } ?>

    42 would be the page id. You can also use the page name and other options. See the codex.

  3. AxelYa
    Member
    Posted 2 years ago #

    racer x, thank you for the answer! I tried this way, but it doesn't catch.
    I tried to place it in different places and include add_action into condition. Nada.
    add_action ignores conditional tag and loads it on any page.

    If this way suppose to work, then I am missing something here. Otherwise, need another approach.

  4. Safirul Alredha (zeo)
    Member
    Posted 2 years ago #

    ...
    function my_map() {
      if (!is_admin() && is_page('42')) {
    ...
  5. racer x
    Member
    Posted 2 years ago #

    My example was a call to the my_map() function within the theme files whether it was index, sidebar, whatever. The function itself could remain in the functions file where it belongs.

    Zeo's idea will work too, but you need to call this function somewhere if the add_action is not working for you.

  6. AxelYa
    Member
    Posted 2 years ago #

    Thank you guys ! I have tried Zeo's way before posting my question. It doesn't load scripts.

    I solved this by replacing add_action('init','my_map') with
    add_action('wp_print_scripts', 'my_map')

    It loads scripts only on chosen page in footer.

    As I am new to all this stuff and I am not a PHP-guy, I am not sure it is proper use of actions and all. I need to learn more about wp_print_scripts

  7. Safirul Alredha (zeo)
    Member
    Posted 2 years ago #

    Oops I missed the init part. Sorry ;)

    see: http://wordpress.org/support/topic/380226

  8. AxelYa
    Member
    Posted 2 years ago #

    Zeo, thanks for the link! I can see that I did it right.
    I might say - resolved

Topic Closed

This topic has been closed to new replies.

About this Topic