0

My website is fully API based and builds pages/posts from API data. I was thinking to create something like PHP magic function __call to call specific function when requested URL would return 404, but do it before it happens, so I could send API request and create the page on the fly and return the previously missing page to user.

What are the options to do it? I know wp_insert_post is the way to add new post via PHP, but I can't find how to hook into initial request before 404 is thrown to initiate wp_remote_request.

Basically I think I miss the filter/action name for it.

Thanks for any help.

2

Simply use template_redirect filter to perform check on request you get in wordpress.

add_filter('template_redirect', 'my_404_override' );

function my_404_override() {
    global $wp_query;

    if (!$wp_query->post) {         // Check if any post is found. If not its 404.
        status_header( 200 );
        $wp_query->is_404=false;

        // Create post object
        $my_post = array(
          'post_title'    => 'My post',
          'post_content'  => 'This is my post.',
          'post_status'   => 'publish',
          'post_author'   => 1,
          'post_category' => array(8,39)
        );

        // Insert the post into the database
        $post_id = wp_insert_post( $my_post );      // Add new post in to the system
        wp_redirect( get_permalink( $post_id ) );   // Finally redirect it to the post.
    }
}

This will create a new post for you & also will redirect user to that post. Well, frankly speaking it's a fix to perform the task but it serves the purpose.

1

If you want to add this logic after WP churns through the query and concludes it's 404, but before it output 404 error page then you likely need to be working in range of logic contained in template-loader.php file.

Most of it is about determining template file for the conditionals fitting current request. You will likely need both to adjust template file choice and probably adjust main WP_Query object and headers.

It seems a little involved to do on the fly. If you don't really need persistent post you might better go the way of creating custom rewrite rules and not follow "post" logic altogether.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.