0
votes

I'm creating a plugin OOP for wordpress. The plugin creates a new custom post type called teams. Within a team page a could use the shortcode [program] to generate some predefault html code. Also i've created custom fields with new meta boxes.

The problem however is: when i'm entering the page thats calling the plugin, equal the team page with the sortcode i need to get post id within my plugin to retrieve get_post_meta().

I've tried the following things:

public function __construct(){
    // not working    
    $post;
    $post->ID;

    // not working
    global $wp_query;
    $post_id = $wp_query->post->ID;

    $post = get_post( $post_id );

    // not workiing
    echo '<pre>';
    print_r('post_id:' . get_the_ID());
    echo '</pre>';
}

How could i receive the custom post id within my plugin when i visited the page from frontend (so the plugin is called, runs the shortcode)

My main class gets loaded like this:

function run_plugin() {

    $plugin = new MyPlugin();
    $plugin->run();
}
run_plugin();

Within MyPlugin the constructor looks like

public function __construct() {    
        if ( defined( 'PLUGIN_NAME_VERSION' ) ) {
            $this->version = PLUGIN_NAME_VERSION;
        } else {
            $this->version = '1.0.0';
        }
        $this->plugin_name = 'MyPlugin';

        if(!empty(get_option($this->plugin_name))){
            $this->clientID = get_option($this->plugin_name)['client_id'];
        }

        $this->load_dependencies();
        $this->set_locale();
        $this->define_admin_hooks();
        $this->define_public_hooks();
        $this->define_shortcodes();
    }
2
I'm confused - why do you have two constructors?FluffyKitten
There the same but with different attempts to solve this issueBham

2 Answers

1
votes

If your plugin constructor is getting called too early, the post data won't be set up and ready to use.

You'll need to hook into one of WPs actions that run after everything is ready. The init action should be enough for the post data, but depending on what else you need you can hook into wp_loaded, as it doesn't run until after WordPress is fully loaded.

function run_plugin() {
    $plugin = new MyPlugin();
    $plugin->run();
}
/* run_plugin(); */                      // <- instead of this....
add_action( 'wp_loaded','run_plugin' );  // <- ...do this
0
votes

Try to define post as global like

global $post