H
H
habrdima2018-06-25 15:20:11
WordPress
habrdima, 2018-06-25 15:20:11

How to add script via php to wordpress?

Here is the code

<?php
global $colWidth;

if(wp_is_mobile()){
    $colWidth = 300;
}else{
    $colWidth = 270; 
}
function f() { ?> 
  <script>
      var a = <?php echo $colWidth; ?>
  </script>
<?php } 
add_action('wp_footer', 'f', 99);

the code is in my plugin
, it adds a script to the footer,
I don’t understand php and wordpress very well, I
found such an addition on the Internet, naturally without a php line in the script,
I don’t understand what kind of addition it is when the f function is in the php area, but the script is not?
and how to add data to var a variable from php?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Yanchevsky, 2018-06-25
@deniscopro

function f() {
  if (wp_is_mobile()) {
    $colWidth = 300;
  } else {
    $colWidth = 270;
  }
  ?> 
  <script>
    var a = <?php echo $colWidth; ?>;
  </script>
  <?php
}

add_action( 'wp_footer', 'f', 99 );

Apparently it's necessary?

A
Ainur Shakirov, 2018-06-25
@Fqyeh29

add_action('wp_footer', 'f', 99);- when the footer is rendered, the function "f" is launched.
In fact, everything outside of F will be executed immediately. You can also put it in F

A
Alexander Sobolev, 2018-06-25
@san_jorich

And why so? Connect js correctly.

function js_includer(){
  //wp_enqueue_script('jquery');
  wp_enqueue_script('js_functions', plugin_dir_url( __FILE__ ). '/footer_js.js');
  wp_localize_script( 'js_functions', 'ajaxurl', admin_url( 'admin-ajax.php' ) );
}
add_action( 'wp_enqueue_scripts', 'js_includer' );

function if_mobile(){
   if(wp_is_mobile()){ $colWidth = 300; } else { $colWidth = 270;  }
   echo $colWidth;
}
add_action( 'wp_ajax_if_mobile', 'if_mobile' );
add_action( 'wp_ajax_nopriv_if_mobile', 'if_mobile' );

And the corresponding footer_js.js
jQuery(document).ready(function() {

jQuery.ajax({
      type:"POST",
      url: ajaxurl,
      data: {
          action: "if_mobile",		     
      },
      success:function(data){ /* Сюда приходит результат php. Не совсем понятно что вы с ним делаете. Возможно Вам нужен JSON и js-изменение ширины окна, блока итд.. для проверки console.log */ console.log(result) },
      error: function(errorThrown){ alert(errorThrown); } 
    });

}
// Код написан в качестве примера. Нужны правки и доработки

In general, it seems to me that you can check for a device / browser, etc. on pure js. Then ajax-turn is superfluous for you. Write a plugin with js connection in which everything is solved.
JS Device Detection
Width Change

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question