Url de ruta de WordPress en el archivo de script js


He añadido script personalizado:

wp_enqueue_script('functions', get_bloginfo('template_url') . '/js/functions.js', 'search', null, false);

Funciona muy bien, excepto en el functions.js tengo:

Reset.style.background = "url('../images/searchfield_clear.png') no-repeat top left";

Esto solía funcionar antes, hasta que cambié a bastante permalinks y .htaccess

La jerarquía de carpetas es como:

themename/js themename/images (las imágenes y la carpeta js están en la carpeta themename)

Lo intenté ../images - ./ image - / images

Normalmente debería retroceder 1 nivel donde se encuentre el archivo js....

No quiero usar completo camino.

¿Hay otra manera que WordPress puede reconocer en el archivo javascript para tener la ruta correcta?

Actualmente estoy confundido sobre lo que estoy haciendo mal.

Author: Jazzepi, 2011-03-07

5 answers

Puede evitar codificar la ruta completa estableciendo una variable JS en el encabezado de su plantilla, antes de llamar a wp_head(), manteniendo la URL de la plantilla. Como:

<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>

Y usa esa variable para establecer el fondo (me doy cuenta de que sabes cómo hacer esto, solo incluyo estos detalles en caso de que ayuden a otros):

Reset.style.background = " url('"+templateUrl+"/images/searchfield_clear.png') ";
 58
Author: AJJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-07 16:07:57

De acuerdo con la documentación de Wordpress, debe usar wp_localize_script() en sus funciones.archivo php. Esto creará un objeto Javascript en el encabezado, que estará disponible para sus scripts en tiempo de ejecución.

Ver Códice

Ejemplo:

<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>

Para acceder a esta variable dentro de Javascript, simplemente haría:

<script type="text/javascript">
    var url = WPURLS.siteurl;
</script>
 89
Author: Chris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-13 18:28:34
    wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);
    wp_enqueue_script('custom-js');

    $wnm_custom = array( 'template_url' => get_bloginfo('template_url') );
    wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );

Y en la costumbre.js

alert(wnm_custom.template_url);
 23
Author: keithics,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-12 17:32:18

Si el archivo javascript se carga desde el panel de administración, esta función javascript le dará la raíz de su instalación de WordPress. Uso esto mucho cuando estoy construyendo complementos que necesitan hacer solicitudes ajax desde el panel de administración.

function getHomeUrl() {
  var href = window.location.href;
  var index = href.indexOf('/wp-admin');
  var homeUrl = href.substring(0, index);
  return homeUrl;
}
 2
Author: Jam Risser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-14 06:03:29

Para usuarios que trabajan con Genesis framework.

Agregue lo siguiente a su tema hijo functions.php

add_action( 'genesis_before', 'script_urls' );

function script_urls() {
?>
    <script type="text/javascript">
     var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';
    </script>
<?php
}

Y use esa variable para establecer la url relativa en su script. Por ejemplo:

Reset.style.background = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";
 0
Author: Toine Pel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-09 12:49:07