Here's What You Need to Know About Writing A WordPress Plugin In C#
Getting Started with a C# Plugin
There are a few PHP compilers out there for .Net that you can employ to write a WordPress plugin in C#. One of the most popular ones is called Phalanger. Phalanger project has made it in such a way that people can run virtually unmodified WordPress clones on .Net. However, there are a few challenges that the project couldn't address, and one of them is the issue of compatibility due to the project having not been compatible with new releases from WordPress. Fortunately, there's a successor of Phalanger, called Peachpie, which has now addressed the issue.
Peachpie, initially released in mid-2016, is an opensource PHP compiler and runtime for .NET and .Net core frameworks. With it, you can be able to write a WordPress plugin in C# efficiently. According to the Czech developer, there are lots of improvements on the Peachpie compiler, which is based on the first-generation Phalanger project. One of them is that Peachpie has an open-source project, called ImageSharp, which helps the compiler to perform similar image function as in PHP. That said, let's take a look at how WordPress plugins in C# work below.
Starting with a dummy plugin for WordPress, plugin.php. For that, we'll use the following code to the right:
<?PHP
/*
Plugin Name: dotNET WordPress Plugin
Description: Basic Plugin in .NET
Version: 20171019
Author: peachpie.io
Author URI: https://www.peachpie.io/
License: Apache
*/
\MyWpPlugin::Register();
Setting up Your WordPress Multisite
Next, we need to implement "MyWpPlugin::Register()" and make it visible to the compiled PHP code. We'll be able to do that by proceeding to create a C# project, "plugin.csproj". Here's how that looks like below.
use Pchp.Core; // Peachpie core API
public class MyWpPlugin {
public static void Register(Context ctx) {
// register callbacks into ctx
}
}
Next, we need a reference to the Peachpie Runtime library('Peachpie.Runtime'). Speaking of that, it contains the API that works with the compiled PHP program. In the code above, the 'Context ctx' parameter is there to help "manipulate the PHP runtime". Apart from that, you can also use it to simulate PHP invokes. Check below for the reference XML snippet, which you can add to the "msbuildproj" file. <ProjectReference Include="..\plugin\plugin.csproj" />
With that, you can now rest assured that everything you implement in your C# code will be available to your PHP code.