Using WordPressSharp To Publish A Post

This is a brief intro to using WordPressSharp to publish a post with C# via the WordPress XML-RPC API.

A few notes… the ‘PostType’ property of the Post class can be set to either “post” or “page” depending on which WordPress type you want to publish. And the ‘Status’ property can be set to either “publish” or “draft” depending on whether you want to publish your new post/page right away or not. In the future I’d like to make these enums or something extendable. But WordPress has them as strings so you can define new ones (ie Custom Post Types) on your own.

Keep in mind this class is merely a simple example. In most cases you might want this in a service layer where you can inject the WordPressSiteConfig class as you need it.

Update: 8/11/2017
There have been a lot of questions about how to add tags and categories to a post since this example contains none. First off – the tag/category/custom taxonomy needs to exist first so you have to create it. Then attach it to the Terms[] collection on the post when creating it. Here’s an example: https://github.com/abrudtkuhl/WordPressSharp/issues/68#issuecomment-321923121

Also – the WordPressSharp nuget package has been updated to the latest and greatest.

Published by

Andy Brudtkuhl

Andy is a full stack web developer, growth hacker, entrepreneur, bike commuter, seinfeld enthusiast, and daddy to three little girls and two dogs in Iowa.

114 thoughts on “Using WordPressSharp To Publish A Post”

        1. client.NewPost will return the WordPress Post Id

          So you can use that ID to build the permalink without making another XML-RPC Call.

          Ex:

          var id = client.NewPost(post);
          var permalink = String.Format(“{0}/?p={1}”, client.BaseUrl, id);

          // permalink = http://brudtkuhl.com/?p=234

          If you have pretty permalinks setup in your admin then it will redirect to it.

    1. You would set the ParentId property on the child page

      var parentPage = new Post {
      PostType = “page”,
      Title = “The Parent Page”,
      Content = “content”,
      PublishDate = DateTime.Now,
      Status = “publish”
      };

      var parentId = client.NewPost(parentPage);

      var childPage = new Post {
      PostType = “page”,
      Title = “The Child Page”,
      Content = “content”,
      PublishDate = DateTime.Now,
      Status = “publish”,
      ParentId = parentId;
      };

      var childId = client.NewPost(childPage);

        1. Yea you can store them in a dictionary if needed. I actually first built this library to move a ton of hierarchical content from a legacy CMS to WP.

          I ended up building a recursive function that handled it nicely. My recursive function had a parameter called parentId that defaults to 0 (if you set it to 0 WordPress knows it’s a top level page). So the function just set it every time and would pass the parent id in from the parent page as it recursed. Worked well.

          1. Great work. Your idea of legacy CMS to WP sounds really interesting. Is it in github somewhere or any change that we can have a look at it? Thanks in advance.

    1. I’m not familiar with that plugin specifically (although it looks awesome and I may need it on a project soon) but after reading the docs briefly you should just be able to add the translations in via the Custom Fields array in the library.

  1. One more: tried with the code above, it failed inside NewPost() when doing

    var termTaxes = post.Terms.GroupBy(t => t.Taxonomy);

    Because post.Terms is null.

    Should I set a default? If I condition that part to post.Terms being not null it works and I can see the post.

    1. using (var client = new WordPressClient())

      {

      var post = new Post

      {

      PostType = “post”,

      Title = “My Awesome Post”,

      Content = “This is the content”,

      PublishDateTime = DateTime.Now.AddDays(1),

      Status = “Draft”

      };

      var t = new Term

      {

      Name = “tag1″+DateTime.Now.ToString(),

      Description = “term description”,

      Slug = “term_test”,

      Taxonomy = “post_tag”

      };

      var termId = client.NewTerm(t);

      t.Id = termId;

      var t2 = new Term

      {

      Name = “cat1” + DateTime.Now.ToString(),

      Description = “cat description”,

      Slug = “term_test”,

      Taxonomy = “category”

      };

      var termId2 = client.NewTerm(t2);

      t2.Id = termId2;

      post.Terms= new Term[]{t,t2};

      var id = Convert.ToInt32(client.NewPost(post));

      Console.WriteLine(id);

      }

        1. Thanks – working on getting a build / package / deploy service setup to keep the nuget.org package in sync with latest code on the master branch of the Github repo

          1. ok, I thought so, but in some cases I only have a word I’d like to add as a tag. So I tried doing a query to find the matching tag and to grab its id, but it returned a bunch of tags that had the word in it… so I guess I need to query, iterate over the results and find the only one that exact matches, and pick it. If I don’t find it, I need to add a new tag and get the id from it. Etc.

  2. I’m trying to add a post with tags associated- Do i need to look up the tags and assign using term id’s, or can i just use terms with names and it will auto-match to existing ones? I tried the latter and had no luck. Thanks.

  3. Andy, this is super useful, thank you. I was just about to sit down and look into preparing something like this myself.

    Custom field options too, awesome! Appreciate the effort.

  4. How can I post image to media gallery into wordpess? I tried using client.Upload function and supplied required values for data. The image goes into the gallery but doesn’t show up, its broken. Any help?

  5. Looks promising, I’m looking for something like this Api, is there more documentation/examples than the “Publish a Post” example?
    Something describing available methods, fields…
    Thanks!

  6. Sorry! would you help me? i can’t post with terms.

    Term keyword = WPClient.GetTerm(“category”, 2);
    var terms = new List();
    terms.Add(keyword);
    var post = new Post();
    post.Title = “TEST”;
    post.Content = “THIS IS TEST”;
    post.PostType = “post”;
    post.Status = “publish”;
    post.PublishDateTime = DateTime.Now;
    post.Terms = terms.ToArray();
    string res = WPClient.NewPost(post);

    but an error happen.

    401
    taxonomy in terms or terms_names is not supported by this post type.

    any suggestion ?

  7. Adjust your code like this :

    TermFilter.cs

    [XmlRpcMember(“number”)]
    public new int Number { get; set; }

    public TermFilter()
    {
    Order = “ASC”;
    OrderBy = “Title”;
    Search = string.Empty;
    Number = int.MaxValue;
    }

    In this way, you can use Number in the term filter !

  8. Hello
    I have to problem

    1- I set username, password, baseURL and Id with “WordPressSiteConfig” class in form1 ! but when i remove or blank these from app.config , it show me error that username,password and … in app.config is blank!
    how should i do ?

    2- how can i define tags for each post ?

  9. Hi
    WordPressSharp not work with VS2013 ? I’m add reference and using WordPressSharp but my vs always show Error 2 The type or namespace name ‘WordPressSharp’ could not be found (are you missing a using directive or an assembly reference?). What’s wrong with me ..

    I’m using VS 2013 and project with .NET 4

    Thanks

  10. hi t
    i used wordpresssharp
    for get catagories List
    it executed successfully in local pc
    but when i tested it in my vps (windows server 2008)
    Error occurred:
    :CookComputing.XmlRpc.XmlRpcServerException: Not Found
    at CookComputing.XmlRpc.XmlRpcClientProtocol.ReadResponse(XmlRpcRequest req, WebResponse webResp, Stream respStm)
    at CookComputing.XmlRpc.XmlRpcClientProtocol.Invoke(Object clientObj, MethodInfo mi, Object[] parameters)
    at XmlRpcProxy14d7ff59-631d-4e61-bd1e-18f519b5e8b9.GetAllCategories(Int32 blog_id, String username, String password)
    at WordPressSharp.WordPressClient.GetCategories()

    help me

      1. I’m constantly getting this same response of “Not Found”

        Stack Trace:
        “at CookComputing.XmlRpc.XmlRpcClientProtocol.ReadResponse(XmlRpcRequest req, WebResponse webResp, Stream respStm)
        at CookComputing.XmlRpc.XmlRpcClientProtocol.Invoke(Object clientObj, MethodInfo mi, Object[] parameters)
        at CookComputing.XmlRpc.XmlRpcClientProtocol.Invoke(MethodInfo mi, Object[] Parameters)
        at XmlRpcProxy6dc5c0ff-164a-49fd-8355-bc8c46bfb355.EditPost(Int32 blog_id, String username, String password, Int32 post_id, Post_Put post)
        at WordPressSharp.WordPressClient.EditPost(Post post)
        at NHL_WordPress_PageUpdate.Program.WpSharp() in ..\Program.cs:line 48
        at NHL_WordPress_PageUpdate.Program.Main(String[] args) in ..\Program.cs:line 22”

        So far this only happens when I attempt to edit a post. I can get a list of post just fine and it won’t error out. I even changed the creds just slightly and ended up with a different error, as expected, so authentication is just fine.

        I have verified that the post does indeed exist, as I can get it directly with the GetPost method using the post id.

        Any ideas?

        PS: What is the purpose of the BlogID property of the WordPressSiteConfig class? I attempted to change it from the value of 1 to the value of the post id, but the same error occurred.

      2. Well, regarding my comment above, just figured out a weird bug.

        The post I was trying to update was a page with an iframe in it. Completely deleting the src attribute sent the request through successfully. Since that worked, I thought it might have something to do with the characters of the url not being parsed correctly. So I sent it through with an empty src attribute, but I still got the error. I then attempted to rename the src attribute to source and the request went through successfully, but of course this is an invalid attribute and didn’t work as expected. Luckily for me, the reason I am doing this is to avoid using an iframe altogether and manually format and deliver my content to the site in an html format. But I really don’t understand why this is an issue.

        Do you?

  11. Hi everybody.
    I should publish a post with a “expire date”. So I added the “PlugIn” “Post Expirator” at my website.
    My question is: how to set the date with this “client” ?.
    P.S. I saw that the plugin inserts a (more than one) row in the table “wp_postmeta” with the string “_expiration-date”.
    Can you help me?
    Best regards

  12. Can anyone give me an example of how to get all the posts or latest posts using it ??

    I’ve tried to use GetPost(); and GetPosts(); but failed 🙁

    1. Nope that call is for WPMU instance I believe. There could be another layer on top of this library to add some helper functions like GetAllPostsByUserId() but for now they dont exist. You’d have to get posts and loop through to check by author. Or we could potentially add an option in the PostFilter class to handle this.

  13. Can I specify multiple tags and categories for a single post using WordPressSnarp? Short example please…
    Thanks.

  14. Hello,
    I have an existing post and every day I have to change it with text. What procedure should i use to make the edit

  15. I just want to say thank u verymuch ! It’s worked. But when i call method newpost this make “Scheduled” status. Not published. I’ll figured out later.

  16. Hi Andy, How do i create post with images. I want send my text with images to wordpress. Can you give me sample code? Thanks Andy

  17. Hi

    CookComputing.XmlRpc.XmlRpcInvalidXmlRpcException: Response XML not valid XML-RPC – root element not methodResponse.

    I’ve tried to use GetPosts():
    public List GetPosts(int PageNumber)
    {
    using (var client = CreateWordPressClient())
    {
    var result = client.GetPosts(new PostFilter { PostType = “post”, PostStatus = “publish”, Number = PageNumber }).OrderByDescending(a => a.Id).ToList();
    return result;
    }
    }

    dgvwPost.DataSource = myWordPressAPI.GetPosts(NumberPostView);

    Please help me!

Leave a Reply

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