e-smartsolution ยป December 1, 2018

Daily Archives: December 1, 2018

Website developer Wordpress

WP, how to add your custom post type by code

Published by:

WP, how to add your custom post type by code

“WordPress can hold and display many different types of content. A single item of such a content is generally called a post, although post is also a specific post type. The table of that contains the posts is “wp_posts” the database that is normally MySQL.”
The default posts types on WordPress are:

  1. Post (Post Type: ‘post’)
  2. Page (Post Type: ‘page’)
  3. Attachment (Post Type: ‘attachment’)
  4. Revision (Post Type: ‘revision’)
  5. Navigation Menu (Post Type: ‘nav_menu_item’)
  6. Custom CSS (Post Type: ‘custom_css’)
  7. Changesets (Post Type: ‘customize_changeset’)
  8. User Data Request (Post Type: ‘user_request’ )
  9. Custom Post Types

The custom Post Types are the new post types. We are going to create a post types “Testimonials”, to do so we will to add
a custom post type to WordPress via the register_post_type() function and this allows us to define a new post type by its labels, supported features, availability and other specifics.

Note that you must call register_post_type() before the admin_menu and after the after_setup_theme action hooks. A good hook to use is the init hook.

1- Create the post type function

function create_post_type() {
  register_post_type( 'esm_testimonials',
    array(
      'labels' => array(
        'name' => __( 'Testimonials' ),
        'singular_name' => __( 'Testimonial' )
      ),
      'public' => true,
      'has_archive' => true,
    )
  );
}
add_action( 'init', 'create_post_type' );
2- Add the above function to your WP
Navigate to WordPress(WP), rootDirectory/wp-content/themes/your-theme/functions.php
wp custom post type

 

3- Check for our Custom post type, on WP admin

We should see on WordPress, www.ourhost.com/wp-admin, our custom post type added. “Testimonials”

4- Optional, add existing category to a Custom post type
The custom post type is created successfully, we want to add an existing category called “Testimonial” our brand new custom type.
// I- Add existing taxonomies to post type testimonials
add_action( ‘init’, ‘wp_add_taxonomies_to_testimonials’ );
function wp_add_taxonomies_to_testimonials() {
register_taxonomy_for_object_type( ‘category’, ‘testimonial’ );
register_taxonomy_for_object_type( ‘post_tag’, ‘testimonial’ );
}

// II. Make Testimonial posts show up in archive pages
add_filter( ‘pre_get_posts’, ‘wptestimonial_add_custom_post_types_to_query’ );
function wptestimonial_add_custom_post_types_to_query( $query ) {
if(
is_archive() &&
$query->is_main_query() &&
empty( $query->query_vars[‘suppress_filters’] )
) {
$query->set( ‘post_type’, array(
‘post’,
‘testimonial’
) );
}
}