I don't understand why use array inside the add action hook to create custom post type using object oriented way

?php
/*
Plugin Name: My Plugin
Plugin URI: https://my.plugin.com
Description: My plugin description
Version: 1.0.0
Author: Me
Author URI: https://my.website.com
License: GPL2 (or whatever)
*/

class myClass {

    function __construct() {

        add_action( 'init', array( $this, 'create_post_type' ) );

    }
    function create_post_type() {
    $name = 'Foos';
        $singular_name = 'Foo';
        register_post_type( 
            $name ,
            array(
                'labels' = array(
                    'name'               = _x( $name, 'post type general name' ),
                    'singular_name'      = _x( $singular_name, 'post type singular name'),
                    'menu_name'          = _x( $name, 'admin menu' ),
                    'name_admin_bar'     = _x( $singular_name, 'add new on admin bar' ),
                    'add_new'            = _x( 'Add New', strtolower( $name ) ),
                    'add_new_item'       = __( 'Add New ' . $singular_name ),
                    'new_item'           = __( 'New ' . $singular_name ),
                    'edit_item'          = __( 'Edit ' . $singular_name ),
                    'view_item'          = __( 'View ' . $singular_name ),
                    'all_items'          = __( 'All ' . $name ),
                    'search_items'       = __( 'Search ' . $name ),
                    'parent_item_colon'  = __( 'Parent :' . $name ),
                    'not_found'          = __( 'No ' . strtolower( $name ) . ' found.'),
                    'not_found_in_trash' = __( 'No ' . strtolower( $name ) . ' found in Trash.' )
                ),
                'public'             = true,
                'has_archive'        = strtolower($taxonomy_name),
                'hierarchical'       = false,
                'rewrite'            = array( 'slug' = $name ),
                'menu_icon'          = 'dashicons-carrot'
            )
        );

    }

}
$my_class = new myClass();
?

Topic custom-post-types Wordpress

Category Web


This is more a PHP question than a WordPress one. WP's add_action and add_filter functions just accept a PHP type known as "callables".

Essentially, when you want to pass an object instance's method as a callback, you do so using the syntax you see here - an array where the first element is the object instance, and the second element is the name of the method.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.