I am using the wpgraphql plugin. For the most part, it is working. However, I can only query posts whose status is published
. Posts with a status of pending
or draft
do not show up.
In other words, here is my query:
query MyQuery {
newsArticles {
nodes {
title
}
}
}
If I set the status of my articles to pending
or draft
, then nothing shows up. If I set them to published
then they do show up.
Note, it does not make any difference if I try a different post type (like posts
) or do the query uses edges
, like this:
query MyQuery {
newsArticles {
edges {
node {
title
}
}
}
}
The results are the same.
So, any idea how to return results regardless of the status?
Thanks.
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.
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.
After the above step, you should be able to see the plugin in your plugins section. Don't activate the plugin now.
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.
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.
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 On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Authorization
header and get non-public postsAuthorization: Bearer ${your_token}
Replace ${your_token}
with your actual token, and you will now be able to query non-public posts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With