Site Loader
Santo Domingo, Dominican Republic
Connecting c# to wordpress
Spread the love

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.

Opening nugget packages in visual studio
Opening nugget packages in visual studio

Then search WordPressPCL and do a right click on Install.

Installing WordPressPCL from nuget packages
Installing WordPressPCL from nuget packages

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.

Supported methods with WordPressPCL
Supported methods with WordPressPCL

Now that you have configured and install 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.

Post Author: Yeison Angomas

I am a software developer and SEO Analyst with more than 5 years of experience using different technologies. My main skills are the development of web applications in .Net, Oracle and SQL Server.

2 Replies to “A Step-by-Step to Connect to WordPress using C Sharp”

  1. Great article for the environment in this sample.
    But what if we have IIS hosted WordPress site, how should we set up the environment and have you tried “JWT Authentication for WP REST API” plugin on a IIS/Windows Server WordPress hosting environment?

  2. Jordan, thanks for your comment.

    In your case WordPress run on PHP the only difference is that is using the IIS Server, unless you’re using other version build in .NET Core. But in the normal scenario your site is running on IIS Server with the PHP module that allow running WordPress.

    You can follow the steps in the same way and it should work always.

    Let me know if that help you.

Leave a Reply

Your email address will not be published. Required fields are marked *