get_post_type on post.php

How can I get the post_type while on the post.php page?

I’m working on a plugin that lets users create a new post type. Then in the new post type, a meta box will be added with some options. The meta box to be added is based on certain parameters that were set while creating the new post type.

Read More

So I need to check what the post_type is, and if it’s a certain post_type, a certain meta box will be added to the post edit page.

I have it working just fine for add new page (post-new.php) using:

$post_type = $_GET[‘post_type’];

But this doesn’t seem to get the post type on the post.php page when editing an existing post within the newly created post type.

I’ve also tried:

$post_type = get_post_type( $post->ID );

and

$post_type = $post->post_type;

Any ideas?

Edit

Example code from comment below:

<?php 
$post_type = get_post_type($post->ID); 
$custom_query = new WP_Query(array( 'post_type' => 'custom-types', 'name' => ''.$post_type.'', 'posts_per_page' => 1 )); 
// STARTS THE LOOP 
while ($custom_query->have_posts()){ 
    $custom_query->the_post(); 
    // GETS POST META VARIABLES 
    global $post; 
    $title = get_the_title(); 
    $option_a = get_post_meta($post->ID, '_option_a', true); 
    $option_b = get_post_meta($post->ID, '_option_b', true); 
} 
?>

Edit

This code works on the post-new.php file:

But not on the post.php file. However, when I fill in the name parameter manually, it works on the post.php file.

The get_post_type($post->ID); is being ignored in the meta boxes on the post.php page, so instead of pulling data from the post with the name of the post type, it’s just pulling data from the most recent post, as if I ran the query without the name parameter at all.

Edit

When I use global $post; no data is pulled from the WP_Query on the post.php page.

With no global $post; the most recent post is pulled from the WP_Query.

When I manually enter the name parameter, it works fine on the post.php page.

The code, as is, works fine on the post-new.php page.

I tried browsing through the source code of the post.php page to see how post_type is referenced there, but no luck. . .figuring out what to use to get the post type.

Related posts

Leave a Reply

2 comments

  1. Why can’t you just globalize $post and then get the post type? e.g.

    <?php
    global $post;
    $post_type = get_post_type( $post->ID );
    ?>
    

    In what context are you placing this code? In a metabox callback, or what?

    (Also: why are you using $_GET data?)

  2. When I changed the loop to

    <?php 
    foreach ($custom_query as $custom) {
    ?>
    

    Instead of

    <?php 
    while ($defaulttheme_query->have_posts()){
        $defaulttheme_query->the_post();    
    ?>
    

    Everything started working.

    For some reason the post type won’t echo within the “while” loop but will within the “foreach” loop.