Run WordPress Hook from Javascript

0

Greetings Friends, I have the following WP Hook:

add_action('template_redirect','random_template');
    function random_template() {
        $posts = get_posts('post_type=post&orderby=rand&numberposts=1');
           foreach($posts as $post) {
             $link = get_permalink($post);
    }
    wp_redirect($link,307);
    exit;
}

And I have the following Javascript code

    $('#Animacion').on("ended", function () {        
        // This does the ajax request
        alert("FIN animacion");
        $.ajax({
                url: "http://url.sitio",
                success: function( data ) {

                }
        })
});    

I need that when an animation that I execute from JS at the end executes the function that I have in WordPress that is a random link, I do not know how to make these two functions connect.

I appreciate a guide.

    
asked by pio 03.06.2017 в 20:01
source

2 answers

1

Wordpress functions are in PHP and run long before the javascript starts running.

In other words, you can not call wordpress functions from javascript.

What you can do is execute the function:

function random_template() {
        $posts = get_posts('post_type=post&orderby=rand&numberposts=1');
           foreach($posts as $post) {
             $link = get_permalink($post);
    }

in advance in the wordpress, to get the link to which you want to redirect and download it to the javascript page using wp_localize_script () to have it available in a variable (array).

Then in the on "end" of the animation rederigirs the link but from javascript adding a location.href = <valor del link en el array javascript bajado desde el wordpress>

    
answered by 03.06.2017 в 20:57
1

Solution:

Thanks to Juan I share the code for the community:

Random Link (Post) - > functions.php

  add_action( 'wp_enqueue_scripts', 'variables_php_js');
  // Función de puesta en cola
  function variables_php_js(){
  global $link;
     $args = new WP_Query(array(
         'posts_per_page'       => '1',
         'no_found_rows'        => true,
         'orderby'              => 'rand',
         'ignore_sticky_posts'  => true,
     ));

     if ( $args->have_posts() ) :
       while ( $args->have_posts() ) : $args->the_post();
         $link = get_permalink(); 
       endwhile;
     endif; wp_reset_query();

    wp_enqueue_script( 'variables-php-js', get_template_directory_uri() . '/js/scripts.js', array( 'jquery' ), false, true );
  wp_localize_script( 'variables-php-js', 'link',array('url' => $link,));
 }

Y The code for the scripts.js file:

$(document).ready(function () {
     $('#Animacion').on("ended", function () {
     location.href = link.url;
     }); 
});

Running an initial animation allows me to redirect randomly to any post in WordPress.

    
answered by 04.06.2017 в 09:42