Search code examples
javascriptphpwordpressplugins

Wordpress plugin onclick function not working


I'm currently creating my own plugin to window.print() a post on my WordPress website. But it seems that I cannot access the function thru the onclick. If I put the window.print() in the button itself it works, but that is not how it has to work for me.

function wpb_follow_us($content) {
  // Only do this when a single post is displayed
  if ( is_single() ) {  
    // Message you want to display after the post
    $content .= '<button type="Submit" value="Print_PDF" 
    onclick="GetPDF()"> Print PDF </button>';
  } 
  // Return the content
  return $content;  
}

But whenever I click the button I get an error that says that it does not access this function:

function GetPDF() {
   window.print();
}

It is in the same file.


Solution

  • Try this:

    // Only do this when a single post is displayed
    if ( is_single() ) { ?>
    
    <script>
    function GetPDF(e) {
        e.preventDefault();
        window.print();
    }
    </script>
     
    <?php 
        // Message you want to display after the post
    
        $content .= '<button type="button" value="Print_PDF" onclick="GetPDF(event)"> Print 
        PDF </button>';
     
        } 
        // Return the content
        return $content;   
        
    }