Search code examples
c#.net-corewordpress-rest-api

How to update a wordpress page from .NET Core


I have downloaded the WordPressPCL example project in https://github.com/wp-net/WordPressPCL.

What I need is to update a page or post of Wordpress but I don't find any example.

All I find are examples of how to get one or many pages or posts, or how to create a new page.

But how to update the date or title of a page? In my attempts I receive "BadRequest" or "NotFound" error responses.

I can get pages without problem doing this:

public async Task<DataTable> LoadPagessAsync()
{
    var client = new RestClient("https://myfoowebname.com/wp-json/wp/v2/"); //obviously this url is fake

    DataTable table = new DataTable();
    table.Columns.Add("ID", typeof(int));
    table.Columns.Add("Title", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    int page = 1;
    bool morePages = true;

    while (morePages)
    {
        var request = new RestRequest($"pages?Authorization=Bearer{Web.Authorization}", Method.Get);
        request.AddParameter("per_page", 100);
        request.AddParameter("page", page);

        var response = await client.ExecuteAsync(request, Method.Get);

        if (response.IsSuccessful)
        {
            var pages = JArray.Parse(response.Content);

            foreach (var pageItem in pages)
            {
                table.Rows.Add(pageItem["id"].Value<int>(), pageItem["title"]["rendered"].Value<string>(), pageItem["date"].Value<DateTime>());
            }

            if (pages.Count < 100)
            {
                morePages = false;
            }
            else
            {
                page++;
            }
        }
        else
        {
            Console.WriteLine("Error getting pages: " + response.ErrorMessage);
            morePages = false;
        }
    }

    return table;
}

And I'm trying to update a page doing this:

public async Task UpdatePageDate(int pageId, DateTime date)
{
    var client = new RestClient("https://myfoowebname.com/wp-json/wp/v2/"); //obviously this url is fake
    var request = new RestRequest($"page/{pageId}?Authorization=Bearer{Web.Authorization}", Method.Post);
    request.AddJsonBody(new { date = date.ToString("yyyy-MM-ddTHH:mm:ssZ") });
    var response = await client.ExecuteAsync(request);

    if (response.StatusCode != HttpStatusCode.OK)
    {
        Console.WriteLine($"Error updating {pageId}: " + response.ErrorMessage);
    }
}

Changing POST to PUT doesn't work either.

Any idea how to do it?


Solution

  • It works perfectly with WordPressPCL library.

    I login with this:

    Client = new WordPressClient(Web.BaseUrl);
    Client.Auth.UseBasicAuth(Username, ApplicationPassword);
    

    Where ApplicationPassword is the password generated in user profile of the Wordpress site.

    And this for update the pages:

    public async Task<List<Page>> UpdatePagesDateAsync(List<Page> pagesToUpdate, DateTime newDate)
    {
        foreach (var page in pagesToUpdate)
        {
            page.Date = newDate;
        }
    
        var updatedPages = await Task.WhenAll(pagesToUpdate.Select(page => Client.Pages.UpdateAsync(page)));
    
        return updatedPages.ToList();
    }
    

    Thx!