fatal error get_page_permastruct()

I’m getting the following error Fatal error: Call to a member function get_page_permastruct() /link-template.php on line 276
when I invoke the in class constructor the wp_insert_post($new_post);.

add_action( 'plugins_loaded', array ( 'test', 'init' ) );
class test{

    public static function init()
    {
        new self;
    }

    //the consructor for parser admin
    function __construct(){

        global $wpdb;
        $this->db = $wpdb;      

        if ($_POST['action'] == 'add-page'){
            add_action( 'plugins_loaded', array ( $this, 'add_newpage' ) );
            $this->add_newpage();
        }
    public function add_newpage(){
        $new_post = array(
                'post_title' => $_POST['page-name'],
                'post_content' => '',
                'post_status' => 'publish',
                'post_type' => 'page'
        );

        $post_id = wp_insert_post($new_post);   
        $newtarget = $this->db->insert( 
                    'wp_test_table', 
                    array( 
                        'post_id' => $post_id, 
                        'slug' => 'test'
                    ), 
                    array( 
                        '%d', 
                        '%s' 
                        ) 
                    );

    }

}

1 Answer
1

This happens because plugins_loaded fires before the global variable $wp_rewrite exists.

From wp-settings.php:

// Load active plugins.
foreach ( wp_get_active_and_valid_plugins() as $plugin )
    include_once( $plugin );
unset( $plugin );

// Load pluggable functions.
require( ABSPATH . WPINC . '/pluggable.php' );
require( ABSPATH . WPINC . '/pluggable-deprecated.php' );

// Set internal encoding.
wp_set_internal_encoding();

// Run wp_cache_postload() if object cache is enabled and the function exists.
if ( WP_CACHE && function_exists( 'wp_cache_postload' ) )
    wp_cache_postload();

do_action( 'plugins_loaded' );

// Define constants which affect functionality if not already defined.
wp_functionality_constants( );

// Add magic quotes and set up $_REQUEST ( $_GET + $_POST )
wp_magic_quotes();

do_action( 'sanitize_comment_cookies' );

/**
 * WordPress Query object
 * @global object $wp_the_query
 * @since 2.0.0
 */
$wp_the_query = new WP_Query();

/**
 * Holds the reference to @see $wp_the_query
 * Use this global for WordPress queries
 * @global object $wp_query
 * @since 1.5.0
 */
$wp_query =& $wp_the_query;

/**
 * Holds the WordPress Rewrite object for creating pretty URLs
 * @global object $wp_rewrite
 * @since 1.5.0
 */
$GLOBALS['wp_rewrite'] = new WP_Rewrite();

Solution: Hook into wp_loaded, not plugins_loaded.

Leave a Comment