Showing Draft and Pending Posts with WpGraphQL Showing Draft and Pending Posts with WpGraphQL wordpress wordpress

Showing Draft and Pending Posts with WpGraphQL


WPGraphQL, by default, only allows public posts to be queried because that is how WordPress works, i.e., only public posts are visible to users.

The first few steps are to add some authentication over our graphql queries so that non-public posts can be queried.

  1. Download this - https://github.com/wp-graphql/wp-graphql-jwt-authentication WordPress plugin either by cloning the repo in plugins directory or uploading the zip file via WordPress.

  2. After the above step, you should be able to see the plugin in your plugins section. Don't activate the plugin now.

  3. Add define('GRAPHQL_JWT_AUTH_SECRET_KEY', 'secret_token'); to your wp-config.php file which is present in the /var/www/html folder. This secret key is used by the plugin to generate tokens to access non-public posts. Ensure the secret token is some random long string that should only be accessible to the WordPress server.

  4. Activate the plugin, and query the following

mutation LoginUser {  login( input: {    clientMutationId: "uniqueId",    username: "your_login",    password: "your password"  } ) {    authToken    user {      id      name    }  }}

You will receive a token that you can use from your code to query non-public posts.

Once the above steps are done, the only thing left is how to use the token and get the non-public posts in your code.

  1. Add SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 in your .htaccess file, which is present in the /var/www/html directory. If you haven't updated your .htaccess file before, it should look like below after updating it. This enables the Authorization header on the incoming request on the WordPress server. We will use the Authorization header to send the authenticated token.
# BEGIN WordPress<IfModule mod_rewrite.c>RewriteEngine OnRewriteBase /RewriteRule ^index\.php$ - [L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dSetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1RewriteRule . /index.php [L]</IfModule># END WordPress
  1. Once the above step is done you will be able to send an Authorization header and get non-public posts
Authorization: Bearer ${your_token}

Replace ${your_token} with your actual token, and you will now be able to query non-public posts.