
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>WordPress &#8211; CodeInDotNet</title>
	<atom:link href="https://www.codeindotnet.com/category/csharp/wordpress/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.codeindotnet.com</link>
	<description>C# Dot Net Programming tutorial &#38; code examples</description>
	<lastBuildDate>Tue, 02 Apr 2024 06:44:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://www.codeindotnet.com/wp-content/uploads/2021/04/SiteIcon.png</url>
	<title>WordPress &#8211; CodeInDotNet</title>
	<link>https://www.codeindotnet.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>WordPress Custom Rest API &#8211; Adding Endpoints</title>
		<link>https://www.codeindotnet.com/wordpress-custom-rest-api-plugin-endpoints/</link>
					<comments>https://www.codeindotnet.com/wordpress-custom-rest-api-plugin-endpoints/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 07 Nov 2023 15:19:07 +0000</pubDate>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[Web API]]></category>
		<category><![CDATA[wordpress api get posts]]></category>
		<category><![CDATA[wordpress web api endpoint integration]]></category>
		<category><![CDATA[wordpress wp rest api json plugin]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=5832</guid>

					<description><![CDATA[Adding WordPress Custom Rest API Plugin Sometimes you prefer to create a custom Rest API in PHP within the context of WordPress to return data in a structured format such as JSON which involves setting up custom routes. Here&#8217;s a step-by-step guide to creating &#38; integrating a basic WordPress Custom REST API in a WordPress [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div id="PageInHoriAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInHoriAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInHoriAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInHoriAd1:', error);
	});
</script>



<br>



<h2 class="wp-block-heading h2Cust1" id="adding-word-press-custom-rest-api-plugin"><strong>Adding WordPress <strong>Custom </strong>Rest API Plugin</strong></h2>



<p class="custp1">Sometimes you prefer to create a custom Rest API in PHP within the context of WordPress to return data in a structured format such as JSON which involves setting up custom routes. Here&#8217;s a step-by-step guide to creating &amp; integrating a basic WordPress Custom REST API in a WordPress plugin.</p>



<br>



<div class="wp-block-rank-math-toc-block toc-cust" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#set-up-a-word-press-plugin">Set up a WordPress Plugin</a></li><li><a href="#define-wp-api-route">Define WP API Route:</a></li><li><a href="#create-api-callback-function">Create API Callback Function</a></li><li><a href="#test-your-api-endpoint">Test Your API Endpoint</a><ul><li><a href="#how-to-find-wp-api-endpoints-or-ur-ls">How to find WP API endpoints or URLs?</a></li><li><a href="#test-wp-web-api-get-method">Test WP Web API &#8211; Get Method()</a></li></ul></li><li><a href="#calling-word-press-custom-rest-api-from-javascript">Calling WordPress Custom Rest API from Javascript</a></li></ul></nav></div>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="set-up-a-word-press-plugin"><strong>Set up a WordPress Plugin</strong></h2>



<br>



<p>Go to &#8216;wp-content/plugins&#8217; directory of your WordPress and create a PHP file (e.g., CustomApi.php) to serve as a <strong>main plugin file</strong>. </p>



<div><b><i><u>cpanel &#8211; File Manger:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/custom-wordpress-rest-api-cpanel-folder.jpg" alt="custom wordpress rest api plugin php file"/></figure>



<p>In this example, the plugin folder and PHP file <em>names</em> are the same. You can rename it.</p>



<p>You can follow simple 3 steps to create and activate a Custom Plugin in the WordPress Dashboard in a few minutes, check this link &#8211; <a href="https://www.codeindotnet.com/create-wordpress-custom-plugin-in-3-steps/" target="_blank" rel="noreferrer noopener"><span class="cLink3"><b>How to Create Custom WordPress Plugin: 3 Easy Steps</b></span></a>.</p>



<br>



<div class="note2">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div style="padding-top:0.4375rem">You can use the function.php file but it&#8217;s best practice to use a separate Plugin for Custom API.</div>
</div>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="define-wp-api-route"><strong>Define WP API Route</strong>:</h2>



<br>



<p>In your plugin file, use the <span class="spanHT">add_action</span> function to hook into WordPress and register your custom API route. Here&#8217;s an example of how to add an API route:</p>



<div><b><i><u>.php file:</u></i></b></div>



<pre class="pchl"><code><span class="key">function</span> registe_api_routes() {
    <b>register_rest_route</b>('<span class="str">PublicAPIs/v1</span>', '<span class="str">/GetTop10Items'</span>,
						<span class="key">array</span>('<span class="str">methods</span>' =&gt; '<span class="str">GET</span>', '<span class="str">callback</span>' =&gt; '<span class="str">CallFun_GetTop10Items</span>',)
						);
}

<b>add_action</b>('<span class="str">rest_api_init</span>', '<span class="str">registe_api_routes</span>');

</code></pre>



<br><br>



<div><b><i><u>Parameter Description:</u></i></b></div>



<figure class="wp-block-table"><table><thead><tr><th>Parameters</th><th>Inputs</th></tr></thead><tbody><tr><td>Namespace</td><td>PublicAPIs/v1</td></tr><tr><td>Endpoint</td><td>GetTop10Items (Public URL)<br>https://yourdomain.com/wp-json/PublicAPIs/v1/GetTop10Items</td></tr><tr><td>Method</td><td>Get method</td></tr><tr><td>callback function name</td><td>CallFun_GetTop10Items<br>(Internal method that executes and sends back responses)</td></tr></tbody></table></figure>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="create-api-callback-function"><strong>Create API Callback Function</strong></h2>



<br>



<p>Define the callback function you specified in the <span class="spanHT">register_rest_route</span> for your API route. This function will handle the request and return the data you want to show via the API.</p>



<p class="custp1">In our example, whenever public API is called by an external source then the below code will be executed internally. </p>



<div><b><i><u>.php file:</u></i></b></div>



<pre class="pchl"><code><span class="key">function</span> CallFun_GetTop10Items() {
	<span class="com">// Your API logic here</span>
	<span class="com">// Example:</span>
	$args =  <span class="key">array</span>('showposts' =&gt; 10, 'orderby' =&gt; 'post_date', 'order' =&gt; 'DESC','post_status' =&gt; 'publish');

	$query_result = query_posts($args);

	$postList = [];

	<span class="key">foreach</span> ($query_result as $result) {
	  $postList[] = array( "post_title" =&gt; $result-&gt;post_title, "post_name" =&gt; $result-&gt;post_name);
	}

	<span class="key">return</span> $postList;
	<span class="com">// or</span>
	<span class="com">// return new WP_REST_Response($postList, 200);</span>
}</code></pre>



<br><br><div><b><i><u>.php code file &#8211; screenshots:</u></i></b></div>



<br><div><b><i><u>Method 1:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/cpanel-php-editor-register-wordpress-rest-route.jpg" alt="create wordpress rest api callback function and register routes"/></figure>



<br><div>You can write the same code in a shorter way.</div>



<div><b><i><u>Method 2:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/cpanel-php-editor-register-wordpress-rest-route-2.jpg" alt="create wordpress rest api callback function and register routes method 2"/></figure>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="test-your-api-endpoint"><strong>Test Your API Endpoint</strong></h2>



<br>



<p>You can now access your API endpoint and check if it is working as accepted.</p>



<br>



<h3 class="wp-block-heading" id="how-to-find-wp-api-endpoints-or-ur-ls"><strong>How to find WP API endpoints or URLs?</strong></h3>



<ul class="wp-block-list">
<li>Open the browser and open the <strong>Inspect </strong>element developer tool as well. (press f12 or right-click &amp; click Inspect)</li>



<li>Go to <strong>https://yourdomain.com/wp-json/</strong> to get wp-json list. </li>



<li>Once it is loaded, navigate and go to <strong>routes</strong></li>



<li>expand and go to the path (namespace/endpoint) that is defined in <span class="spanHT">register_rest_route</span> method, that is &#8216;<strong>PublicAPIs/v1/GetTop10Items</strong>&#8216;</li>



<li>Get the API (full URL) as shown in the below screenshot. <br><em><strong>example:</strong></em> https://yourdomain.com/wp-json/PublicAPIs/v1/GetTop10Items</li>
</ul>



<br>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/find-wordpress-api-list-wp-json.jpg" alt="find wp rest api list wp-json"/></figure>



<br><br>



<h3 class="wp-block-heading" id="test-wp-web-api-get-method"><strong>Test WP Web API &#8211; Get Method()</strong></h3>



<p class="custp1">Get API can be executed directly on the browser but for demo purposes, we will use the Postman tool to test our API.</p>



<p>The below screenshot demonstrates that a Get API request sends back a response as a JSON result via Postman tool.</p>



<p><strong><em>Test API:</em></strong> https://yourdomain.com/wp-json/PublicAPIs/v1/GetTop10Items</p>



<div><b><i><u>wordpress api get posts:</u></i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="/img/wp/api/wordpress-rest-api-response-result.jpg" alt="wordpress rest api response result"/></figure>



<br><br><br>



<h2 class="wp-block-heading hLBRed" id="calling-word-press-custom-rest-api-from-javascript"><strong>Calling WordPress Custom Rest API from Javascript</strong></h2>



<br>



<p>You can use the <span class="spanHT">fetch</span> method in Javascript to call and get the response from the WordPress Custom Rest API, as demonstrated below.</p>



<pre class="pchl"><code>&lt;script>

document.addEventListener("DOMContentLoaded", LoadLatestPosts);

<span class="key">async function</span> LoadLatestPosts() {

	<span class="key">const</span> response = <span class="key">await</span> fetch('<span class="str" style="background:#fafbbb;">/wp-json/PublicAPIs/v1/GetTop10Items</span>');
	<span class="key">const</span> data = <span class="key">await</span> response.json();

	data.<span class="key">forEach</span>(obj => {
		// your logic
	});

}

&lt;/script></code></pre>



<br><div class="note2">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div style="padding-top:0.375rem">You might get an error if the full URL is given with the domain name, so specify the internal URL in the fetch method as mentioned in the code.</div>
</div>



<div id="PageInAd1"></div>
<script>
fetch('https://www.codeindotnet.com/gads/PageInAd1.txt')
	.then(response => response.text())
	.then(text => {
		document.getElementById('PageInAd1').innerHTML = text;
	})
	.catch(error => {
		console.error('Error fetching manual PageInAd1:', error);
	});
</script>



<br>
<script src="/my-js/latesttop10post.js" type="text/javascript"></script>
<input type="hidden" id="cids" value="3,59,71">
<div id="latestPostlist"></div>
<br><br>



<p>for more details check this link: <a href="https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/" target="_blank" rel="noopener"><strong>https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/</strong></a></p>



<style>
.toc-cust{
border:1px solid #add8e6;
padding-top: 15px;
padding-left:15px;
}
.toc-cust h2{
font-weight:bold;
font-size: 1.5rem;
color:#ba3925e3;
}
</style>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/wordpress-custom-rest-api-plugin-endpoints/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Create Custom WordPress Plugin: 3 Easy Steps</title>
		<link>https://www.codeindotnet.com/create-wordpress-custom-plugin-in-3-steps/</link>
					<comments>https://www.codeindotnet.com/create-wordpress-custom-plugin-in-3-steps/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 02 May 2023 08:57:00 +0000</pubDate>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[plugin]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=3575</guid>

					<description><![CDATA[A custom plugin is an alternative method of storing functions for your website. WordPress is so popular because of its open-source content management system (CMS) and there are over millions of plugins widely available but we will see how to create plugin in WordPress with examples and adding custom codes instead of using a function.php [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>



<p>A custom plugin is an alternative method of storing functions for your website. WordPress is so popular because of its open-source content management system (CMS) and there are over millions of plugins widely available but we will see how to create plugin in WordPress with examples and adding custom codes instead of using a function.php file</p>



<br>



<div class="wp-block-rank-math-toc-block toc-cust ul1"><h2><span style="text-decoration: underline;">Table of Contents</span></h2><nav><ul><li class=""><a href="#reason-to-avoid-function-php-file">Reason to avoid function.php file</a></li><li class=""><a href="#how-to-create-a-word-press-plugin-in-3-steps">How to Create a WordPress Plugin (In 3 Steps)</a><ul><li class=""><a href="#step-1-create-the-plugin-file">Step 1: Create the Plugin File</a></li><li class=""><a href="#step-2-install-custom-plugin-into-word-press">Step 2: Install Custom Plugin into WordPress</a></li><li class=""><a href="#step-3-edit-plugin-add-code">Step 3: Edit Plugin &amp; Add Code</a></li></ul></li></ul></nav></div>



<br><br>



<h2 class="wp-block-heading" id="reason-to-avoid-function-php-file"><strong>Reason to avoid function.php file</strong></h2>



<br>



<p>You can also include additional code in the theme’s functions.php file but whenever there is a theme update or switching to a different theme in the future, you will lose these changes(additional codes). And every time you must back up your custom codes whenever there is a theme update. </p>



<p>To avoid such a problem, you can create your own plugin and use custom code in that. <strong>Benefit </strong>&#8211; The theme update won&#8217;t affect the plugin code.</p>



<p>Now, we will see how to create plugin in PHP (text file) and add it in WordPress. </p>



<br><br>



<h2 class="wp-block-heading" id="how-to-create-a-word-press-plugin-in-3-steps"><strong>How to Create a WordPress Plugin (In 3 Steps)</strong></h2>



<br>



<p>Recommendation &#8211; It is best practice to create a new Plugin in the local environment first and after successful testing deploy it in the live environment. </p>



<p>Let’s look at how to create a plugin for a website from scratch in 3 steps</p>



<br>



<h3 class="wp-block-heading" id="step-1-create-the-plugin-file"><strong>Step 1: Create the Plugin File</strong></h3>



<br>



<p>Open a new Notepad or text file.</p>



<p>Provide basic information for a new plugin, mentioned below:</p>



<figure class="wp-block-table is-style-regular"><table><tbody><tr><td>Plugin Name</td><td>any name, e.g., MyPlugin</td></tr><tr><td>Plugin URI</td><td>give your URL, e.g., https://google.com/</td></tr><tr><td>Description</td><td>Short note</td></tr><tr><td>Version</td><td>any number, e.g., 1</td></tr><tr><td>Author</td><td>any name</td></tr></tbody></table></figure>



<br>



<p>Copy &amp; paste the below code into the notepad. Code should start with <span class="spanHT">&lt;?php</span></p>



<pre class="wp-block-code"><code>&lt;?php
/*
Plugin Name: <strong>MyPlugin</strong>
Plugin URI: https://google.com/
Description: My custom functions
Version: 1
Author: Myself
*/
</code></pre>



<p>Save the file, example &#8211; <strong>MyPlugin.php</strong>. </p>



<br>



<div><b><i>Screenshot</i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/wp/create_custom_plugin_wordpress.jpg" alt="create custom plugin wordpress"/></figure>



<br><br>



<div>
Next, <strong><span style="text-decoration: underline;">zip the php file</span></strong> (MyPlugin.php)
<br>
<div style="padding-left:10px">
<strong>&#8211;</strong> right-click on file <br><strong>&#8211;</strong> go to &#8216;<strong>Send to</strong>&#8216; <br><strong>&#8211;</strong> click on <strong>Compressed (zipped) folder</strong>.
</div>
</div>



<br><br><div><b><i>Screenshot</i></b></div>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/wp/zip-custom_plugin_php_file.jpg" alt="zip custom plugin php file"/></figure>



<br><br>



<h3 class="wp-block-heading" id="step-2-install-custom-plugin-into-word-press"><strong>Step 2: Install Custom Plugin into WordPress</strong></h3>



<br>



<p>1. Go to WordPress admin (https://www.yoursite.com/wp-admin)</p>



<p>2. go to &#8211; <strong>Plugin </strong>&gt;&gt; <strong>Add New</strong></p>



<p>3. Click on &#8216;<strong>Upload Plugin</strong>&#8216;</p>



<p>4. &#8216;<strong>Choose file</strong>&#8216; and upload the zip file (MyPlugin.zip) </p>



<p>5. Click on &#8216;<strong>Install Now</strong>&#8216;</p>



<p>6. After successful Installation, click on &#8216;<strong>Activate Plugin</strong>&#8216;</p>



<p>Click on <strong>Plugins</strong>, you can see the newly created custom Plugin with the description as shown in the below screenshot. </p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/wp/custom_plugin_screenshot.jpg" alt="custom plugin screenshot"/></figure>



<br><br>



<h3 class="wp-block-heading" id="step-3-edit-plugin-add-code"><strong>Step 3: Edit <strong>Plugin</strong> &amp; Add Code</strong></h3>



<br>



<p>Next, go to <strong>Plugin</strong> &gt;&gt; <strong>Plugin File Editor</strong> </p>



<p>On the top-right,  select the custom plugin &#8216;<strong>MyPlugin</strong>&#8216; from the dropdown and click the &#8216;<strong>Select</strong>&#8216; button.</p>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/wp/edit_custom_plugin_wordpress.jpg" alt="edit_custom_plugin_wordpress"/></figure>



<br>



<p>Write your php code in the editor and click on &#8216;<strong>Update</strong> <strong>File</strong>&#8216; </p>



<p>That&#8217;s it, test your code if it is working as expected.</p>



<br><br>



<div style="padding: 0.625rem 1.25rem 1.25rem 1.25rem; box-shadow: 0.0625rem 0.0625rem 0.9375rem 0rem lightgrey; margin-bottom: 1.25rem; border-radius: 0.625rem;">
<div><span style="border-bottom: 0.0625rem solid #cd5c5c; color:#cd5c5c;"><b><i>read also:</i></b></span>
<div style="padding-left:0.9375rem; padding-top:0.625rem; line-height: 1.9;">
<div><b>– <a href="https://www.codeindotnet.com/extract-images-from-pdf-using-itext7-c-net/">How to extract images from PDF using iText7 in C# .Net Code</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/what-is-dapper-micro-orm-in-c/">What is Dapper micro-ORM in C#?</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/how-to-integrate-mailchimp-v3-0-api-in-dotnet-core-c/">How to Integrate MailChimp v3.0 API in DotNet Core C#</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/export-dataset-to-excel-in-c-net-core-openxml/">Export DataSet To Excel in C# .Net Core – OpenXml</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/dynamically-add-anchor-tag-in-div-html-javascript/">Dynamically generate anchor tag in div HTML  javascript</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/wordpress-rest-api-c-wordpresspcl-example/">Easy Integration of WordPress API in C# .Net</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/find-sitemap-website-url-link-is-exists-valid-c-dot-net-core/">Check SiteMaps XML URL Nodes for broken links C#</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/insert-tab-white-spaces-in-text-html-css-code/">Insert tab spaces characters in text – HTML CSS</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/create-image-tag-after-countdown-timer-finishes-javascript/">Display an Image tag after countdown timer finishes JavaScript</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/how-to-use-dynamic-parameters-in-dapper-2-0-in-c-net-core/">How To Use Dynamic Parameters In Dapper 2.0 In C# .Net Core?</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/what-is-api-application-programming-interface/">What is an API – Application Programming Interface</a></b></div>
<div><b>– <a href="https://www.codeindotnet.com/sonarlint-code-clean-up-for-ms-visual-studio-cyclomatic-complexity-explained/">SonarLint Code Clean-up for MS Visual Studio &amp; Cyclomatic Complexity Explained</a></b></div>
</div>
</div>
</div>



<p>Reference: <a href="https://wordpress.org/documentation/article/plugins-editor-screen/" target="_blank" rel="noopener">WordPress</a></p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.codeindotnet.com/create-wordpress-custom-plugin-in-3-steps/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Easy Integration of WordPress API in C# .Net</title>
		<link>https://www.codeindotnet.com/wordpress-rest-api-c-wordpresspcl-example/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 28 Mar 2023 12:13:47 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[WordPress]]></category>
		<guid isPermaLink="false">https://www.codeindotnet.com/?p=2375</guid>

					<description><![CDATA[In this post, we will see how to integrate WordPressPCL Nuget Package to connect and work with the WordPress website using REST APIs in C# .Net application. WordPress software is written in PHP and it is difficult for other programming developers to adopt additional skills and make changes in the code. The good thing is, [&#8230;]]]></description>
										<content:encoded><![CDATA[
<br>



<p>In this post, we will see how to integrate WordPressPCL Nuget Package to connect and work with the WordPress website using REST APIs in C# .Net application. WordPress software is written in PHP and it is difficult for other programming developers to adopt additional skills and make changes in the code. The good thing is, .Net developers can make use of the WordPressPCL library in C# which acts as an interface to allow external applications to access the data and functionality of the WordPress CMS via REST API calls.</p>



<div><span style="border-bottom: 1px solid #800000; color:#800000;"><b>Table of Content</b></span></div>



<div style="padding-left:20px; padding-top:5px;">
<div><b>&#8211; <a href="#apppassword" data-type="internal" data-id="#apppassword">Create Application Password for WordPress API</a></b></div>
<div><b>&#8211; Implementation of WordPress API Code</b></div>
	<div style="padding-left:20px;">
	<div><b>&#8211; <a href="#integratewp" data-type="internal" data-id="#integratewp">Integrate WordPressPCL Nuget package</a></b></div>
	<div><b>&#8211; <a href="#wpauth" data-type="internal" data-id="#wpauth">WordPress API authentication (Basic, JWT)</a></b></div>
	<div><b>&#8211; WordPress <strong>CRUD</strong> Rest API Calls (Create, Read, Update, Delete)</b></div>
		<div style="padding-left:20px;">
		<div><b>&#8211; </b><a href="#postapis" data-type="internal" data-id="#postapis"><strong>WP-Post</strong></a></div>
		<div><b>&#8211; </b><a href="#categoryapis" data-type="internal" data-id="#categoryapis"><strong>Category</strong></a></div>
		<div><b>&#8211; </b><a href="#tagapis" data-type="internal" data-id="#tagapis"><strong>Tag</strong></a></div>
		</div>
	</div>	
</div>



<br><br>



<h2 class="h2Cust1" id="apppassword"><b>Create Application Password for WordPress API</b></h2>



<p style="margin-top: 2.1rem; margin-bottom: 0.3rem;">The first step is to create an Application Password which will be used in the code for authentication purposes. </p>



<ul class="wp-block-list">
<li>Login into WordPress admin portal (https://www.YourDomain.com/<strong>wp-admin</strong>).</li>



<li>Go to <strong>User &gt;&gt; Profile</strong> page. </li>



<li>Generate the password by providing an Application Name.</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/wp/create-wordpress-application-password.jpg" alt="create-wordpress-application-password"/></figure>



<br><br>



<h2 class="h2Cust1" id="impwpapicode"><b>Implementation of WordPress API Code C#</b></h2>



<p>Next, integrate the WordPressPCL library in the .Net application and write methods in a static class using C# code to call WordPress Rest APIs.</p>



<h2 class="wp-block-heading" id="integratewp"><strong>Integrate WordPressPCL Nuget Package</strong></h2>



<ul class="wp-block-list">
<li>Create a new .Net application </li>



<li>Install <a href="https://www.nuget.org/packages/WordPressPCL" target="_blank" rel="noopener"><strong>WordPressPCL</strong></a> Nuget Package</li>
</ul>



<figure class="wp-block-image size-large"><img decoding="async" src="https://www.codeindotnet.com/img/wp/wordpresspcl-nuget-package.jpg" alt="wordpresspcl-nuget-package"/></figure>



<p>or use the following command line in Console to install the package </p>



<div style="background:#08090a; color:#f8f8f2; width:80%; border-radius: 0.375rem; padding-top: 10px; padding-bottom: 10px;">
<span style="padding-left:15px">Install-Package WordPressPCL -Version 2.0.0</span>
</div>



<br><br>



<h2 class="wp-block-heading" id="wpauth"><strong>WordPress API authentication C#</strong></h2>



<ul style="padding:5px 0px 0px 40px; margin-bottom:0px;">
<li style="margin: 0px;">Create a common static class and methods that can perform WordPress API requests (CRUD operations).</li>
</ul>



<pre class="pchl"><code><span class="key">public</span> <span class="key">static</span> <span class="key">class</span> WordPress
{
} </code></pre>



<br>



<ul style="padding:0px 40px; margin-bottom:0px;">
<li style="margin: 0px;">Add the following namespaces</li>
</ul>



<pre class="pchl"><code><span class="key">using</span> WordPressPCL;
<span class="key">using</span> WordPressPCL.Models; </code></pre>



<br>



<ul class="wp-block-list">
<li>Use <strong><span class="spanHT">&#8216;<strong>WordPressClient</strong>&#8216; class</span></strong> to get authenticated and connect with the WordPress client. 
<ul class="wp-block-list">
<li>Pass the default Rest API <strong>URL as a parameter</strong> in the constructor. <br>e.g., https://YourDomain.com/<strong>wp-json</strong></li>



<li>Pass your registered Application username &amp; password for <span class="spanHT">authentication</span>. <br>You can <strong>use either <span class="spanHT">Basic</span> or <span class="spanHT">JWT Token</span> (Bearer) for authentication</strong></li>
</ul>
</li>
</ul>



<pre class="pchl"><code><span class="com">//<b>Method 1)</b> <u>Basic Authentication</u></span>
wpClient.Auth.UseBasicAuth(<span class="str">"WpApiUserName"</span>, <span class="str">"JEs8 xxWpPasswordxx 98JW iKK3 98Jw"</span>);

<span class="com">//Or</span>

<span class="com">//<b>Method 2)</b> <u>JWT(Bearer) Authentication</u></span>
wpClient.Auth.UseBearerAuth(<span class="custkey">JWTPlugin</span>.JWTAuthByEnriqueChavez);
wpClient.Auth.RequestJWTokenAsync(<span class="str">"username"</span>, <span class="str">"password"</span>);
<span class="key">var</span> isValidToken = wpClient.Auth.IsValidJWTokenAsync;
</code></pre>



<br><br>



<h2 class="h2Cust1" id="postapis"><b>CRUD Rest API C# Code for WordPress Post</b></h2>



<p>Below is the full code for WP-Post which performs CRUD operation using WordPress Rest APIs</p>



<h2 class="wp-block-heading"><strong>Create WP-Post C# Code</strong></h2>



<button class="c-b-s-f-r" onclick="ctc('div1',this)">Copy code</button>
<br>
<div id="div1">
<pre class="pchl"><code><span class="key">using</span> WordPressPCL;
<span class="key">using</span> WordPressPCL.Models;

<span class="key">namespace</span> Data
{
    <span class="key">public</span> <span class="key">static</span> <span class="key">class</span> <span class="custkey">WordPress</span>
    {
        <span class="key">public</span> <span class="key">static</span> <span class="key">async</span> <span class="custkey">Task</span> CreateOrUpdatePost(<span class="custkey">DataObject</span> dataObj)
        {
            <span class="com">// Get valid WordPress Client</span>
            <span class="custkey">WordPressClient</span> wpClient = <span class="key">new</span> <span class="custkey">WordPressClient</span>(<span class="str">"https://YourDomain.com/wp-json/"</span>);

            <span class="com">//Basic Auth</span>
            wpClient.Auth.UseBasicAuth(<span class="str">"WpApiUserName"</span>, <span class="str">"JEs8 xxWpPasswordxx 98JW iKK3 98Jw"</span>);

            <span class="com">//Or, Bearer Auth using JWT tokens</span>
            <span class="com">//wpClient.Auth.UseBearerAuth(JWTPlugin.JWTAuthByEnriqueChavez);</span>
            <span class="com">//wpClient.Auth.RequestJWTokenAsync("username", "password");</span>
            <span class="com">//var isValidToken = wpClient.Auth.IsValidJWTokenAsync;</span>

            <span class="com">//Create and Set Post object</span>
            <span class="key">var</span> post = <span class="key">new</span> <span class="custkey">Post</span>
            {
                Title = <span class="key">new</span> <span class="custkey">Title</span>(dataObj.Title),
                Meta = <span class="key">new</span> <span class="custkey">Description</span>(dataObj.Description),
                Excerpt = <span class="key">new</span> <span class="custkey">Excerpt</span>(dataObj.Excerpt),
                Content = <span class="key">new</span> <span class="custkey">Content</span>(dataObj.Content),
                <span class="com">//slug should be in lower case with hypen(-) separator </span>
                Slug = dataObj.Slug
            };

            <span class="com">// Assign one or more Categories, if any</span>
            <span class="key">if</span> (dataObj.Categories.Count &gt; 0)
            {
                post.Categories = dataObj.Categories;
            }

            <span class="com">// Assign one or more Tags, if any</span>
            <span class="key">if</span> (dataObj.Tags.Count &gt; 0)
            {
                post.Tags = dataObj.Tags;
            }

            <span class="key">if</span> (dataObj.PostId == 0)
            {
                <span class="com">// if you want to hide comment section</span>
                post.CommentStatus = <span class="custkey">OpenStatus</span>.Closed;
                <span class="com">// Set it to draft section if you want to review and then publish</span>
                post.Status = <span class="custkey">Status</span>.Draft;
                <span class="com">// Create and get new the post id</span>
                dataObj.PostId = <span style="background:#f2f19d;">wpClient.Post.CreateAsync(post).Result.Id</span>;

                <span class="com">// read Note section below - Why update the Post again?</span>
                <span class="key">await</span> wpClient.Posts.UpdateAsync(post);
            }
            <span class="key">else</span>
            {
                <span class="com">// check the status of post (draft or publish) and then update</span>
                <span class="key">if</span> (IsPostDraftStatus(wpClient, dataObj.PostId))
                {
                    post.Status = <span class="custkey">Status</span>.Draft;
                }

                <span style="background:#f2f19d;"><span class="key">await</span> wpClient.Posts.UpdateAsync(post)</span>;
            }
        }

        <span class="key">private</span> <span class="key">static</span> <span class="key">bool</span> IsPostDraftStatus(<span class="custkey">WordPressClient</span> client, <span class="key">int</span> postId)
        {
            <span class="key">var</span> result = <span style="background:#f2f19d;">client.Posts.GetByIDAsync(postId, <span class="key">true</span>, <span class="key">true</span>).Result</span>;

            <span class="key">if</span> (result.Status == <span class="custkey">Status</span>.Draft)
            {
                <span class="key">return</span> true;
            }
            <span class="key">else</span>
            {
                <span class="key">return</span> false;
            }
        }
    }
} </code></pre>
</div>



<br>



<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Note:</div>
<div class="notepoints" style="padding-top:0.375rem">Why update the Post again?<br>
Actually, it is not required but I encountered a problem when creating a bulk WP Post (more than 100) and noticed that many Post&#8217;s slug name is the same as the title name even though I gave different slug names. That&#8217;s the reason &#8211; calling the update method again. Implement if it is required.</div>
<div class="notepoints">Make sure to check the WP Post&#8217;s status before updating it next time. As per my scenario, I am creating Post and doing changes multiple times in the draft status via code and publishing it later.</div>
</div>



<br>



<p>Call <strong>CreateOrUpdatePost()</strong> static method from other class. The below code shows how to set the properties of a Post and <strong>generate content</strong> (from the database).</p>



<button class="c-b-s-f-r" onclick="ctc('div2',this)">Copy code</button>
<br>
<div id="div2">
<pre class="pchl"><code><span class="key">public</span> <span class="key">async</span> <span class="key">void</span> PostTodaysContent()
{
	<span class="key">try</span>
	{
		<span class="key">var</span> dbContent = _context.NextPosts.Where(w =&gt; w.Name == <span class="str">"Today"</span>).FirstOrDefault();

		<span class="custkey">DataObject</span> dataObj = <span class="key">new</span> <span class="custkey">DataObject</span>()
		{
			PostId = dbContent.PostId,
			Title = <span class="str">"Sample title"</span>,
			Description = <span class="str">"This is description"</span>,
			Content = GenerateContent(dbContent),
			Slug = dbContent.Slug <span class="com">// or "this-is-sample"</span>
		};

		<span class="com">// Existing WP Category IDs</span>
		dataObj.Categories = <span class="key">new</span>() { 111, 112 };

		<span style="background:#f2f19d;"><span class="key">await</span> <span class="custkey">WordPress</span>.CreateOrUpdatePost(dataObj);</span>

		<span class="key">if</span> (dbContent.PostId == <span class="key">null</span> || dbContent.PostId == 0)
		{
			dbContent.PostId = dataObj.PostId;
			_context.SaveChanges();
		}
	}
	<span class="key">catch</span> (<span class="custkey">Exception</span> ex)
	{

	}
} </code></pre>
</div>



<br>



<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Suggestion:</div>
<div style="padding-top:0.375rem">If you are targeting standard Categories or Tags then better to create them manually in WP-Admin Portal and use its existing IDs in the code.<br>How to find Id? &#8211; Click on any Category or Tag and find the Id in the URL.<br><img decoding="async" src="https://www.codeindotnet.com/img/wp/find-category-tag-id-wordpress.jpg" alt="find-category-tag-id-wordpress"><br>But you can generate them dynamically through code if that is the requirement, please see the Categories and Tags code section below.</div>
</div>



<br>



<div class="noteimpwar">
<div style="color:#dc2323; font-weight:bold; border-bottom:0.125rem #dc2323 solid; font-style:italic;">Note:</div>
<div style="padding-left:0.375rem; padding-top:0.375rem">It is a very rare situation but it is important to know that sometimes new WP-Post does not reflect in the WP-Admin portal immediately even though the API code generated and returned a new PostId. In my case, this issue occurred one time during the bulk process and it took 4 hours for a new post to get visible in the portal. If you got a new PostId via code then wait and don&#8217;t create the same (duplicate) post again, until you are sure it has not been created.</div>
</div>



<br>



<h2 class="wp-block-heading"><strong>Generate HTML Content &#8211; Sample</strong></h2>



<button class="c-b-s-f-r" onclick="ctc('div3',this)">Copy code</button>
<br>
<div id="div3">
<pre class="pchl"><code><span class="key">private</span> <span class="key">static</span> <span class="key">string</span> GenerateContent(NextPosts dbContent)
{
	<span class="com">// sample content</span>
	StringBuilder sb = <span class="key">new</span> StringBuilder();
	sb.Append(<span class="str">"&lt;h2&gt; "</span> + dbContent.Header + <span class="str">"&lt;/h2&gt;"</span>);
	sb.Append(<span class="str">"&lt;div&gt;"</span>);
	sb.Append(dbContent.Column2 + <span class="str">"&lt;br&gt;"</span>);
	sb.Append(<span class="str">"&lt;table&gt;"</span>);
	sb.Append(<span class="str">"&lt;tr&gt;&lt;td&gt;"</span> + dbContent.Column3 + <span class="str">"&lt;/td&gt;&lt;/tr&gt;"</span>);
	sb.Append(<span class="str">"&lt;/table&gt;"</span>);
	sb.Append(<span class="str">"&lt;/div&gt;"</span>);

	<span class="key">return</span> sb.ToString();
} </code></pre>
</div>



<br>



<h2 class="wp-block-heading"><strong>Get WP-Post C# Code</strong></h2>



<button class="c-b-s-f-r" onclick="ctc('div4',this)">Copy code</button>
<br>
<div id="div4">
<pre class="pchl"><code><span class="com">// get all</span>
<span class="key">var</span> getAllPosts = <span class="key">await</span> wpClient.Posts.GetAllAsync();
<span class="com">// get by id</span>
<span class="key">var</span> getPostbyid = <span class="key">await</span> wpClient.Posts.GetByIDAsync(postId);

<span class="com">// Get Posts Count</span>
<span class="key">var</span> postsCount = <span class="key">await</span> wpClient.Posts.GetCountAsync(); </code></pre>
</div>



<br>



<h2 class="wp-block-heading"><strong>Delete WP-Post C# Code</strong></h2>



<button class="c-b-s-f-r" onclick="ctc('div5',this)">Copy code</button>
<br>
<div id="div5">
<pre class="pchl"><code><span class="com">// delete Post by id</span>
<span class="key">bool</span> isDeleted = wpClient.Posts.DeleteAsync(postId).Result;
</code></pre>
</div>



<br><br>



<h2 class="h2Cust1" id="categoryapis"><b>WordPress Category CRUD REST API C# Code</b></h2>



<p>CRUD operation API calls (create, read, update and delete) for Category.</p>



<button class="c-b-s-f-r" onclick="ctc('div6',this)">Copy code</button>
<br>
<div id="div6">
<pre class="pchl"><code>
<span class="custkey">Category</span> category = <span class="key">new</span> <span class="custkey">Category</span>
{
	Name = <span class="str">"Sales"</span>,
	Slug = <span class="str">"new-sales"</span>,
	<span class="com">// If it is a sub-category then mention Parent(existing) category Id</span>
	Parent = 111
};

<span class="com">// create</span>
<span class="key">var</span> wpc = wpClient.Categories.CreateAsync(category).Result;
<span class="key">int</span> categoryId = wpc.Id; <span class="com">// e.g. 10</span>

<span class="com">// update category by id</span>
<span class="custkey">Category</span> category = <span class="key">new</span> <span class="custkey">Category</span>
{
	Name = <span class="str">"Rename Sales"</span>,
	<b>Id = 10</b>,
};
<span class="key">await</span> wpClient.Categories.UpdateAsync(category);

<span class="com">// get all categories</span>
<span class="key">var</span> getAllCategories = <span class="key">await</span> wpClient.Categories.GetAllAsync();

<span class="com">// get category by id</span>
<span class="key">var</span> getCategoryById = <span class="key">await</span> wpClient.Categories.GetByIDAsync(categoryId);

<span class="com">// delete Category by id</span>
<span class="key">bool</span> isDeleted = wpClient.Categories.DeleteAsync(categoryId).Result; </code></pre>
</div>



<br><br>



<h2 class="h2Cust1" id="tagapis"><b>WordPress Tag CRUD REST API C# Code</b></h2>



<p>Code for consuming the Tag REST-APIs</p>



<button class="c-b-s-f-r" onclick="ctc('div7',this)">Copy code</button>
<br>
<div id="div7">
<pre class="pchl"><code>
<span class="custkey">Tag</span> tag = <span class="key">new</span> <span class="custkey">Tag</span>
{
	Name = <span class="str">"books"</span>,
	Slug = <span class="str">"new-books"</span>,
};

<span class="com">// create</span>
<span class="key">var</span> wptag = wpClient.Tags.CreateAsync(tag).Result;
<span class="key">int</span> tagId = wptag.Id; <span class="com">// e.g. 20</span>

<span class="com">// update tag by id</span>
<span class="custkey">Tag</span> tag= <span class="key">new</span> <span class="custkey">Tag</span>
{
	Name = <span class="str">"Rename books"</span>,
	<b>Id = 20</b>,
};
<span class="key">await</span> wpClient.Tags.UpdateAsync(tag);

<span class="com">// get all tags</span>
<span class="key">var</span> getAllTags = <span class="key">await</span> wpClient.Tags.GetAllAsync();

<span class="com">// get tag by id</span>
<span class="key">var</span> getTagById = <span class="key">await</span> wpClient.Tags.GetByIDAsync(tagId);

<span class="com">// delete tag by id</span>
<span class="key">bool</span> isDeleted = wpClient.Tags.DeleteAsync(tagId).Result; </code></pre>
</div>



<br><br>



<div><b>Getting WP-Post Comments Code</b></div>



<button class="c-b-s-f-r" onclick="ctc('div8',this)">Copy code</button>
<br>
<div id="div8">
<pre class="pchl"><code><span class="key">var</span> comm = <span class="key">await</span> wpClient.Comments.GetAllAsync();
<span class="key">var</span> commById = <span class="key">await</span> wpClient.Comments.GetByIDAsync(id);
<span class="key">var</span> commByPostId = <span class="key">await</span> wpClient.Comments.GetCommentsForPostAsync(postId, <span class="key">true</span>, <span class="key">false</span>); </code></pre>
</div>



<br><br>



<div class="noteimpwar">
<div style="color:#dc2323; font-weight:bold; border-bottom:0.125rem #dc2323 solid; font-style:italic;">Note:</div>
<div style="padding-left:0.375rem; padding-top:0.375rem">I run this code in a local environment and usually generate more than 50 (bulk) WP-Post using &#8216;foreach loop&#8217;. One time, I got a notification of duplicate &#8216;Page Indexing&#8217; from Google Search Console<br><b><i>message</i></b> &#8211; Duplicate, Google chose different canonical than user)<br><b><i>reason</i></b> &#8211; Same post got created two times and the duplicate URL had &#8220;-2&#8221; at the end.<br><b><i>solution</i></b> &#8211; as per my requirement i am handling it in two ways:</div>
<div class="notepoints">not using <span style="color: #0000ff;"><b><i>await</i></b></span> in few lines of code even though it is <span style="color: #0000ff;"><b><i>async</i></b></span> method</div>
<div class="notepoints">written a separate code that will compare sitemap URLs with stored slug names in the database, to make sure all bulk post is generated and there are no duplicates.</div>
</div>



<br>



<div class="note">
<div style="color:#00008b; font-weight:bold; border-bottom:0.125rem #00008b solid; font-style:italic;">Suggestion:</div>
<div style="padding-top:0.375rem">As one or more post is getting generated through code, it is better to validate all &#8216;new &amp; old&#8217; URLs, periodically. Check this link &#8211; <a href="https://www.codeindotnet.com/find-sitemap-website-url-link-is-exists-valid-c-dot-net-core/" aria-current="page"><b>How to Read XML Sitemap and validate URLs (links exists or not)</b></a></div>
</div>



<p></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
