WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Custom Post Type single page (2 posts)

  1. robmuzo
    Member
    Posted 1 year ago #

    Hi,

    Is it possible to have a custom post type that is singular?

    i.e

    Using a custom post type to make an editable home page that would only show edit rather than add new home page once 1 was added?

    Thanks

  2. robmuzo
    Member
    Posted 1 year ago #

    This does the Job

    /**
     * Plugin Name: Home Page CPT
     **/
    
    class WP_Homepage_CPT {
    
        function __construct() {
    
            // add the default homepage on plugin activation
            register_activation_hook( __FILE__, array( &$this, 'add_home_page_post' ) );
    
            // register the homepage post type
            add_action( 'init', array( &$this, 'register_homepage_cpt' ) );
    
            // add the menu link
            add_action( 'admin_menu', array( &$this, 'edit_homepage_link' ) );
        }
    
        function edit_homepage_link() {
            global $submenu, $pagenow;
    
            // query the homepage posts
            $homepage = new WP_Query( 'post_type=homepage' );
    
            // if its new post page and we have homepage
            if ( $pagenow == 'post-new.php' && $homepage->have_posts() ) {
                wp_die('You cant add more then one homepage');
            }
    
            // if we have homepage post, show the edit link else the add homepage link
            if ( $homepage->have_posts() ) {
                $homepage->the_post();
                $link = get_edit_post_link( get_the_ID(), 'return' );
                $title = 'Edit Home Page';
            } else {
                // in case if the user has deleted the default post
                $link = get_bloginfo( 'url' ). '/wp-admin/post-new.php?post_type=homepage';
                $title = 'Add Home Page';
            }
            $submenu['edit.php'] = array( array( $title, 'manage_options', $link ) ) + $submenu['edit.php'];
        }
    
        function register_homepage_cpt() {
            $args = array(
                'label' => 'homepage',
                'description' => 'Home Page post type',
                'public' => true,
                'show_in_menu' => false
            );
            register_post_type( 'homepage', $args );
        }
    
        function add_home_page_post() {
            // on activation first regsiter the post type
            $this->register_homepage_cpt();
    
            // add the first and only post
            $post_data = array(
                'post_title' => 'Home Page',
                'post_type' => 'homepage',
                'post_statue' => 'publish',
                'post_author' => 1
            );
            wp_insert_post( $post_data );
        }
    
    }
    
    $GLOBALS['wp_homepage_cpt'] = new WP_Homepage_CPT;

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.