DEV Community

Yeison Lapaix
Yeison Lapaix

Posted on • Updated on • Originally published at yeisonpx.com

Connecting to WordPress using C#

alt text

In this post, we will see how to connect to Wordpress website using C# and make publications using WordpressPCL library in three easy steps.

Wordpress is a great CMS that allow developers and people that don't need a lot of software development skills to create websites with awesome functionalities. Therefore, is one of the most popular tools uses actually to build websites.

This CMS is very flexible to create custom functionalities, although is very possible that exists like a plugin that can be installed to the site. Wordpress has a big community of developer with a lot of experience with the platform where you can find solutions for almost all the issue you can have.

The thing with Wordpress is that was built in PHP, so if you don't know the language you can lose time in the process to learn and then implement what you want to do.

Next, We will see how to configure a visual studio project with c# to connect to a website with Wordpress, that is a good solution for .Net developers that don't have good knowledge of PHP.

1. Configure Wordpress API in your website

First of all, you need to configure your site to have enabled the API that allows reading and writing on WordPress. The prerequisites to connect to Wordpress with WordpressPCL is to install the following plugins in your website:

Then to complete de JWT configuration is necessary to add some modifications to the .htaaccess file:

  • First, enable HTTP Authorization Header adding the following:
    RewriteEngine on
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

 

  • Then enable the WPENGINE adding this code in the same .htacess file:

    SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

The JWT needs a secret key to sign the token this secret key must be unique and never revealed.

To add the secret key edit your wp-config.php file and add a new constant called JWT_AUTH_SECRET_KEY.

    define('JWT_AUTH_SECRET_KEY', 'your-top-secrect-key');

 

You can generate and use a string from here https://api.wordpress.org/secret-key/1.1/salt/

You can see all the details from the documentation here.

2. Install WordpressPCL from Nuget Packages

Now you need to install the Wordpress nuget package from Visual Studio called WordpressPCL. To open nugget packages manager do right click on your project in Visual Studio and then click to Manage Nuget Package.

alt text

Then search WordPressPCL and do a right click on Install.

alt text

You can also install the packages using the nuget packages console inserting the following commands:

Install-Package WordPressPCL -Version 1.5.0

What you can do with WordpressPCL? Well, the following table shows the supported methods that you have access to uses.

alt text

Now that we have configured and installed all that you need, let's see how we can create, update and query data from Wordpress.

Example 1: Connecting to Wordpress

To connect to Wordpress client you can use the class WordPressClient that accept in his constructor the  URL of your website. Example http://domain-example.com/wp-json/. Where the /wp-jon/ is the default path to the Wordpress REST API.

private static async Task<WordPressClient> GetClient()
        {
            // JWT authentication
            var client = new WordPressClient("http://wordpress-domain.com/wp-json/");
            client.AuthMethod = AuthMethod.JWT;
            await client.RequestJWToken("user", "password");
            return client;
        }

Example 2: Creating and Updating Data

using System;
using System.Linq;
using System.Threading.Tasks;
using WordPressPCL;
using WordPressPCL.Models;

namespace WordPressTest
{
    class Program
    {
        static void Main(string[] args)
        {
            CreatePost().Wait();
        }

        private static async Task CreatePost()
        {
            try
            {
                WordPressClient client = await GetClient();
                if (await client.IsValidJWToken())
                {
                    var post = new Post
                    {
                        Title = new Title("New post test"),
                        Content = new Content("Content for new post.")
                    };
                    await client.Posts.Create(post);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:" + e.Message);
            }
        }

        private static async Task<WordPressClient> GetClient()
        {
            // JWT authentication
            var client = new WordPressClient("http://wordpress-domain.com/wp-json/");
            client.AuthMethod = AuthMethod.JWT;
            await client.RequestJWToken("user", "password");
            return client;
        }
    }
}

Example 3: Getting data

To query data is easy as you can see below:


    var client = GetClient();

    //Getting all the post
    var posts =await client.Posts.GetAll();

    //Getting one post
     var onePost = await client.Posts.GetByID(1);

You can download these examples from my Github account in the project WordpressTest and for more information about the WordpressPCL API, you can check the official documentation here: Github WordpressPCL Documentation.

I hope that I can help you to have a good introduction to of how to connect with a Wordpress website using .Net.

Please let me know if you have any dude.

Original post: Step By Step to Connect to Wordpress Using C Sharp

Top comments (12)

Collapse
 
whitear27 profile image
Audrey White

Hi, this post has been super helpful to me. I am a student developing a Xamarin iOS app for a current Wordpress WooCommerce site. I was able to retrieve the products and display within the app. I can also add products, however I am unable to upload images from my iPhone into the WordPress wp-content library. Is there a way to upload images directly to the wp-content media library with WordPress PCL?
Thank you for this post!

Collapse
 
yeisonpx profile image
Yeison Lapaix

Hi Audrey, thanks to you for your feedback. You can upload images using the client.Media object and methods. For example:

 var createdMedia = await client.Media.Create(@"C:\pathToFile\media.jpg","media.jpg");

Check more details here in the documentation: Working with Medias

I hope this can help you.

Collapse
 
mohammedtuhami330 profile image
MohammedTuhami330

Object reference not set to an instance of an object" mean?

Collapse
 
mohammedtuhami330 profile image
MohammedTuhami330

I want to connect using application password !
can i ?

Collapse
 
esklad profile image
esklad

When I connect to your site:
demo.wp-api.org/wp-json/
everything is working!
And when to my: bonito-market.ru/wp-json/
That get an error:
Unexpected character encountered while parsing value: p. Path ', line 0, position 0.
What would that mean ?!

Collapse
 
esklad profile image
esklad

With the new version of WordPress, your WordpressPCL library is not working. As in the new version of WordPress returns not JSON, but HTML!
According to the Wireshark
It's true?

Collapse
 
rmehling profile image
Robert Mehling

This worked great for me. Thank you very much for sharing!

Collapse
 
cognicsystems profile image
Cognic

Hello @yeisonpx
Thanks for the article, Drawing inspiration from your post, we have restructured the process to align with the latest conditions , please take a look and let me know your thought.

Collapse
 
rainocode profile image
rainocode

Connecting to a WordPress site using C# opens up a world of possibilities for developers looking to interact with WordPress programmatically. In this comprehensive guide, we'll walk you through the process of establishing a connection to a WordPress site using C#, enabling you to retrieve data, update content, and automate website management tasks.
for more information visit link:
rainocode.com/blog/connecting-to-w...

Collapse
 
esklad profile image
esklad

And one more question:
Does your "WordpressPCL" work with Products and WooCommerce (Orders)?

Collapse
 
yeisonpx profile image
Yeison Lapaix

Hello, thanks for your response.

I never try with WooCommerce, but I suppose products are post types and you can try publishing a post with setting the property of Type with Product.

First consult the posts with the WordpressPCL library and then check if also retrieve the products and which type of post is.

Let me know if that work for you.

Collapse
 
esklad profile image
esklad

The programmer did not solve the problem:
studiofreya.com/2018/06/04/problem...