How to Create Custom Posts without using plugins

Step1: Copy and paste the Below code in your theme "function.php". Here i am using this code to create Cusotm Post for "Testimonials", We can Rename it as required

<?php add_action('init', 'testimonials_init');
function testimonials_init()
{
    $feature_labels = array(
        'name' => _x('Testimonials', 'post type general name'), // Name which displays in dashboard
        'singular_name' => _x('Testimonial', 'post type singular name'),
        'all_items' => __('All Testimonials'),
        'add_new' => _x('Add new Testimonial', 'director'),
        'add_new_item' => __('Add new Testimonial'),
        'edit_item' => __('Edit Testimonial'),
        'new_item' => __('New Testimonial'),
        'view_item' => __('View Testimonial'),
        'search_items' => __('Search in Testimonial'),
        'not_found' =>  __('No Testimonial found'),
        'not_found_in_trash' => __('No Testimonial found in trash'),
        'parent_item_colon' => ''
    );
    $args = array(
        'labels' => $feature_labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => 5,
        'supports' => array('title', 'editor','thumbnail'), //  Delete this if thumbnail is not required
        'has_archive' => 'testimonial'
    );
    register_post_type('testimonial',$args); // Post type ID
}
?>

Step2: Copy  and paste this code in your Template to display posts  
Note: Change "post_type=testimonial" if you changed it in the above code

<?php
$my_query = new WP_Query('post_type=testimonial&posts_per_page=-1'); // "-1" describs to display all posts , You can Restrict posts by using positive values
while ($my_query->have_posts()) : $my_query->the_post();
?>
 <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> // Post Title
<div class="thumbnail">
<?php the_post_thumbnail();?> // Post Thumbnail
</div>
<div class="entry">
      <?php the_content(); ?> // Post Content
    </div>
<?php endwhile; ?>
   

No comments:

Post a Comment