Can you add a shortcode to a custom post type that gets the post_title, post_content, etc. and then passes that to a plugin function?
Help! Cannot figure this out.
I have built a plugin based on this tutorial that gives a user the ability to export a post from a custom post type into a formatted PDF using FPDF.
As it stands, the PDF export works, but the current post is not being passed to the plugin function. A button is added to the post via a custom shortcode. When clicking the button, it is supposed to automatically take the currently viewed post and produce a PDF of the content. I can input a specific post ID into the function and it exports that specific post as intended. If I just use get_post with no argument, it exports a PDF of post with ID=1 that has already been trashed, regardless of which post the shortcode button is in.
As an FYI, the posts are loaded via AJAX, so could the problem have something to do with that?
What am I doing wrong?! Is there a better way to do this? I appreciate your help!
lsmg-pdf.php
<?php
/*
* Plugin Name: [redacted]
* Description: A plugin created to apply PDF export functionality to documents.
* Version: 1.0
* Author: [redacted]
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
include( 'lsmg-pdf-helper-functions.php');
$pdf = new PDF_HTML();
if( isset($_POST['generate_posts_pdf'])){
output_pdf();
}
function output_pdf() {
$post = get_post();
global $pdf;
$title_line_height = 10;
$content_line_height = 8;
$pdf->AddFont( 'Lato', '', 'Lato-Regular.php' );
$pdf->AddFont( 'Lato', 'B', 'Lato-Bold.php' );
$pdf->AddFont( 'Lato', 'I', 'Lato-Italic.php' );
$pdf->SetMargins(12.7, 12.7);
$pdf->SetDrawColor(36,161,89);
$pdf->AddPage();
$pdf->SetFont( 'Lato', 'B', 24 );
$pdf->SetTextColor(4,23,51);
$pdf->Write($title_line_height, $post->post_title);
$pdf->SetLineWidth(1);
$pdf->Line(14, 27, 40, 27);
// Add a line break
$pdf->Ln(14);
// Image
$page_width = $pdf->GetPageWidth() - 20;
$max_image_width = $page_width;
$image = get_the_post_thumbnail_url( $post->ID );
if( ! empty( $image ) ) {
$pdf->Image( $image, null, null, 100 );
}
// Post Content
$pdf->Ln(10);
$pdf->SetFont( 'Lato', '', 10 );
$pdf->SetTextColor(38,59,71);
$pdf->WriteHTML($post->post_content);
$pdf->Output('D','lsmg-guideline-doc.pdf');
exit;
}
function lsmg_pdf() {
?>
<div class="wrap">
<form method="post" id="as-fdpf-form">
<button class="custom-botton" type="submit" name="generate_posts_pdf" value="generate">Download PDF</button>
</form>
</div>
<?php
}
function register_shortcodes(){
add_shortcode('fpdf-doc', 'lsmg_pdf');
}
add_action( 'init', 'register_shortcodes');
Leave an answer