从插件

时间:2019-01-10 12:44:04

标签: php wordpress post global

我正在尝试访问global $post对象,并将当前页面ID传递到在products帖子类型的管理屏幕中生成PDF的函数中。但是,在运行函数时,我不断收到错误'Trying to get property 'ID' of non-object'

我在woocommerce_init()动作中使用全局$ post调用该函数。

有人知道我为什么继续收到错误消息吗?

add_action( 'woocommerce_init', 'my_function_with_wc_functions' );
function my_function_with_wc_functions() {
if( isset($_POST['generate_posts_pdf'])) {
  global $post;
  output_pdf($post->ID);
}
}

add_action('add_meta_boxes', 'as_fpdf_add_custom_box');
function as_fpdf_add_custom_box()
{
    $screens = ['product'];
    foreach ($screens as $screen) {
        add_meta_box(
            'as_fpdf_box_id',           // Unique ID
            'Entry List',  // Box title
            'as_fpdf_create_admin_page',  // Content callback, must be of type callable
            $screen,                   // Post type
            'normal'                  // Priority
        );
    }
}

add_action( 'admin_menu', 'as_fpdf_create_admin_menu' );
function as_fpdf_create_admin_menu() {
    $hook = add_submenu_page(
        'tools.php',
        'Atomic Smash PDF Generator',
        'Atomic Smash PDF Generator',
        'manage_options',
        'as-fdpf-tutorial',
        'as_fpdf_create_admin_page'
    );
}

function output_pdf($id) {
    global $wpdb;

        if ( $wpdb->get_var( $wpdb->prepare( 'SELECT lottery_id FROM ' . $wpdb->prefix . 'wc_lottery_log WHERE lottery_id = %d', $id) ) ) {

      $log = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'wc_lottery_log WHERE lottery_id=%d', $id );

      global $pdf;
      $title_line_height = 10;
      $content_line_height = 8;

      $pdf->AddPage();
      $pdf->SetFont( 'Arial', '', 42 );
      $pdf->Write(20, 'Atomic Smash FPDF Tutorial');

      foreach( $log as $row ) {

          $pdf->SetFont( 'Arial', '', 22 );
          $pdf->Write($title_line_height);

          // Add a line break
          $pdf->Ln(15);

          // Post Content
          $pdf->Ln(10);
          $pdf->SetFont( 'Arial', '', 12 );
          $pdf->WriteHTML($row->ticketid);
        }

    }

    $pdf->Output('D','atomic_smash_fpdf_tutorial.pdf');
    exit;
}


function as_fpdf_create_admin_page() {
?>
<div class="wrap">
    <h1>Generate Entry List</h1>
    <p>Click below to generate a pdf all all lottery entries. </p>
      <form method="post" id="as-fdpf-form">
        <button class="button button-primary" type="submit" name="generate_posts_pdf" value="generate">Generate PDF from Competiion Entries</button>
    </form>
</div>

<?php
}

0 个答案:

没有答案