2

I want to allow Facebook (user agent facebookexternalhit) to access scheduled posts before they're published, so it can access meta information in order to schedule a status. Currently I temporarily publish posts, schedule Facebook statuses, and then unpublish and schedule posts via WordPress.

When a WordPress post is scheduled, editors can access the pre-published page but everybody else is shown a 404 when the URL is visited. How can I allow a certain user agent (i.e. Facebook) to access posts too before they're published?

1

Create a new plugin with the following code:

class Facebook_Peeker {
    private static $facebook_bots = [
        'facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)',
        'facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)'
    ];

    private $original_posts;

    public function make_scheduled_post_public() {
        add_filter( 'posts_results', [ &$this, 'peek_into_private' ], null, 2 );
    }

    public function peek_into_private( $posts, &$query ) {
        if ( sizeof( $posts ) != 1 ) {
            return $posts;
        }

        $status = get_post_status_object( get_post_status( $posts[0] ) );
        if ( $status->public ) {
            return $posts;
        }

        $this->original_posts = $posts;
        add_filter( 'the_posts', [ &$this, 'override_private' ], null, 2 );
    }

    public function override_private( $posts, &$query ) {
        remove_filter( 'the_posts', [ &$this, 'peek_into_private' ], null, 2 );
        return $this->original_posts;
    }

    private function is_facebook_seeking() {
        return in_array( $_SERVER[ 'HTTP_USER_AGENT' ], self::$facebook_bots );
    }

    public static function init() {
        if ( ! self::is_facebook_seeking() ) {
            return;
        }

        $peeker = new Facebook_Peeker();
        $peeker->make_scheduled_post_public();
    }
}

add_action( 'plugins_loaded', [ 'Facebook_Peeker', 'init' ] );

This allows the Facebook bot to see scheduled posts but disallows the rest of the public to see. Remember to update any relevant caching settings if using other plugins.

Answer derived with the help of How to make scheduled post preview visible to anyone? and How to recognize Facebook User-Agent.

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.