WordPress最佳做法,在激活挂钩上调用函数

时间:2020-02-28 17:07:15

标签: wordpress

我正在使用PHP class创建目录列表插件,但没有__construct()方法可用。

final class ShibbirDirectoryListing
{
    /**
     * create pages and setup the plugin tables
     * 
     * @since 1.0.0 
     */
    public function initial_setup()
    {

        $login_page_title = 'login';
        $login_page_content = 'login page content';
        $login_page_check = get_page_by_title($login_page_title);
        $login_page = array(
            'post_type' => 'page',
            'post_title' => $login_page_title,
            'post_content' => $login_page_content,
            'post_status' => 'publish',
            'post_author' => 1,
            'post_slug' => 'login'
        );
        if (!isset($login_page_check->ID) && ! $this->is_slug_exists('login')) {
            $login_page_id = wp_insert_post($login_page);
        }
    }

    /**
     * Check if the page is eixst
     * 
     * @since 1.0.0 
     */
    public function is_slug_exists($post_name)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'posts';
        if ($wpdb->get_row("SELECT post_name FROM {$table_name} WHERE post_name = '" . $post_name . "' ", ARRAY_A)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Main ShibbirDirectoryListing Instance
     * 
     * Ensure only one instance of ShibbirDirectoryListing is loaded
     *      
     * @since 1.0.0
     * @static
     * @return ShibbirDirectoryListing - Main instance
     */
    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
            self::$instance->setup();
        }

        return self::$instance;
    }

}


/**
 * Register plugin settings
 */
register_activation_hook( __FILE__, array( 'ShibbirDirectoryListing', 'initial_setup' ) );

/**
 * Get the instance of the plugin 
 */
function shibbir_directory_listing()
{
    return ShibbirDirectoryListing::instance();
}

// Let's start the Engine
shibbir_directory_listing();

在这里您可以看到我需要在register_activation_hook及其initial_setup的调用class方法上创建一些页面。

initial_setup方法中,我需要调用另一个名为is_slug_exists的方法。但是我对此调用有一个错误,因为那时它还不在类上下文中。 / p>

那么在这里调用is_slug_exists方法的最佳方法是什么?

1)我可以在is_slug_exists方法中使用initial_setup 功能代码吗?
2)是否可以在register_activation_hook方法中使用__construct,然后调用is_slug_exists方法?
3)如果我选择 2),那么instance()静态方法真的必要吗?
4) OR 我应该在register_activation_hook上调用函数而不是调用类方法吗?

0 个答案:

没有答案