Building WordPress Plugin Using FPDF – How do you get post content from currently viewed post?

I am using FPDF to build a plugin in wordpress that will add a button on each post(documentation) that gives the user the ability to export it as a styled pdf from the post without having to maintain working files and uploading attachements for hundreds of files.

I used this as a guide, and it currently works in one respect, however this current iteration exports a PDF of ALL posts in the documentation post type. How do I instead pull the post content from the currently viewed post only?

I have been banging my head for a week, so hopefully someone can point me in the right direction. Let me know if I can clarify anything additional.

Thanks!

<?php

if ( ! defined( 'ABSPATH' ) ) {
exit;
}

include( 'atomicsmash-pdf-helper-functions.php');

$pdf = new PDF_HTML();

if( isset($_POST['generate_posts_pdf'])){
output_pdf();
}

function output_pdf() {
$args = array(
    'post_type'   => 'manual_documentation'
  );

$posts = get_posts( $args );

if( ! empty( $posts ) ) {
    global $pdf;
    $title_line_height = 10;
    $content_line_height = 8;

    foreach( $posts as $post ) {

        $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','atomic_smash_fpdf_tutorial.pdf');
exit;
}

function as_fpdf_create_admin_page() {

?>

<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', 'as_fpdf_create_admin_page');
}

add_action( 'init', 'register_shortcodes');

0

Leave a Comment