skip to Main Content

Im currently creating my own plugin to window.print a post on my WordPress website.
But it seems that i cannot acces 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.

 
// 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 acces this function:

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

It is in the same file.

2

Answers


  1. The HTML element’s onclick attribute looks for a javascript function, it cannot run a PHP function.

    See this question

    Login or Signup to reply.
  2. 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;   
        
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search