Sergio Solorzano
Sergio Solorzano

Reputation: 667

How execute existing shortcode in wp with javascript

I am using PDF Embedder to embed pdf into wp webpage.

I'd like it to embed pdf when a button is clicked.

When I add the pdf media PDF Embedder inserts shortcode in backend editor:

[pdf-embedder url="http://example.com/wp-content/uploads/securepdfs/2019/11/nameofpdf.pdf"]

I created a js button onlick function to execute this shortcode

<script>
function EmbedPDF(){
[pdf-embedder url="http://example.com/wp-content/uploads/securepdfs/2019/11/nameofpdf.pdf"];
}
</script>

However when clicking button I get error on console:

Uncaught SyntaxError: Unexpected token '<'

<a href="/?pdfemb-serveurl=http%3A%2F%2Fexample.com%2Fwp-content%2Fuploads%2Fsecurepdfs%2F2019%2F11%2Fnameofpdf.pdf" class="pdfemb-viewer" style="" data-width="max" data-height="max" data-mobile-width="500"  data-scrollbar="none" data-download="off" data-tracking="on" data-newwindow="on" data-pagetextbox="off" data-scrolltotop="off" data-startzoom="100" data-startfpzoom="100" data-download-nonce="f55003eba4" data-disablerightclick="on" data-toolbar="bottom" data-toolbar-fixed="off">titleofpdf<br/></a>;

Upvotes: 0

Views: 483

Answers (1)

Kradyy
Kradyy

Reputation: 345

As previous poster mentioned PHP Shortcodes are excecuted on the server-side thus cannot be excecuted via direct Javascript, for this you can make an AJAX call (depending on the type of output you're expecting)

You could try something as follows (untested but i think youäll get the idea) :)

This code goes into your functions.php file:

<?php
// Load your custom js file
function my_enqueue() {
    wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/custom.js', array('jquery') );
    // Here we need to send the ajax_urladmin-ajax url as a variable to the external JS file since we can't use PHP to get the URI in Javascript
    wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

// Add a method for opeing the PDF
function loadPDF() {
    $url = isset($_REQUEST["post_id"]) ? $_REQUEST["post_id"] : null;

    if(!$url) // { } Handle invalid URL / Perform checks

    echo do_shortcode('[pdf-embedder url="'.$url.'"]');
}

// Define our ajax hooks
// wp_ajax_nopriv_ = for visitors
// wp_ajax_ = for logged in users
add_action( 'wp_ajax_loadPDF', 'loadPDF' );
add_action( 'wp_ajax_nopriv_loadPDF', 'loadPDF' );
?>

This code goes into your custom js file:

jQuery( document ).ready() {
    jQuery('.pdf-button').on('click', function() {
        // Get the URL that should be loaded
        var url = jQuery(this).data('url');

        jQuery.ajax({
            type: "post",
            url : ajax_object.ajaxurl,
            data : {action: "loadPDF", url: url},
            success: function(data){
                // Redirect the output to a container ie. div
                jQuery('.my-container').html(data);
            }
        });
    });
});

Example HTML:

<div class="btn pdf-button" data-url="http://example.com/wp-content/uploads/securepdfs/2019/11/nameofpdf.pdf">
</div>

<div class="my-container">
<!-- PDF Output -->
</div>

Upvotes: 1

Related Questions