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.

This article was written by ss

Sanjib Sinha is an Author, and Full Stack Web Developer.

He writes stories; as well as codes. His book “The Beginning Ethical Hacking with Python” (Apress) has been one of the most downloaded IT books in 2016-17 (Provided by Bookmetrix). Know his journey as a writer: http://sanjibsinha.com.

He loves to connect through his social media handle: @sanjibsinha.

Leave a Reply

Your email address will not be published. Required fields are marked *