Custom Post Type in WordPress for PHP Developers

Sometimes you need a custom post type in your WordPress application.
Let me explain why you need it first?
Wordpress comes up with two basic types of Posts. One is Post and the other is Page. People often get misguided and think WordPress is just a blog engine and a content management system on a PHP platform.
This concept is wrong.
Wordpress is a sleeping giant whom you need to poke and tweak to get things done on your whim. Just make it talk, it’ll actually sing! Such is the power of WordPress.
In default Pages or Posts you may add plenty of contents and you can also categorize them, no problem.
But a custom post type is the symbol of your freedom. You’re going to do something with it that simple Page and Post could not do. You can extend your Custom Post Type to eternity. Unthinkable and unbelievable are the possibilities.
The process is extremely simple.
Add this code to your ‘functions.php’:

// ADD CUSTOM POST TYPE
add_action('init', 'create_post_type');
function create_post_type() {
    
    register_post_type('custom-content',
            array(
                'labels' => array(
                    'name' => __('Custom Content'),
                    'singular_name' => __('Custom Content')
                ),
                'public' => TRUE,
                'has_archive' => true
            ));
    
}

On the left side of your Admin Dashboard panel you get it. Just click and it’ll open. Now you can add any type of content here. Text, Image and Video.
Want to show it on your Home page?
Very simple. On the ‘front-page.php’ add this code:


$args = array( 'post_type' => 'generic-content', 'posts_per_page' => 10 );
$the_query = new WP_Query( $args ); 
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
the_title(); 
the_content(); 
wp_reset_postdata();  
endwhile; else:
_e( 'Sorry, no posts matched your criteria.' );
endif;

Besides on your front page you want to show the Custom content on a dedicated page. Create a ‘single-custom-content.php’ page and just paste the code of your ‘page.php’. You need to get the title and content, so it’s not difficult at all.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s