You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用wordpress-java库发布文章到指定WordPress分类?

How to Publish a Post to a Specific Category with wordpress-java

Hey there! Let's break down exactly how to publish a post to your "General" category using the wordpress-java library. The key thing to note here is that the library uses category IDs (not names) to associate posts with categories, so we'll first fetch the ID for your target category, then attach it to your post before publishing.

Step 1: Fetch the ID of the "General" Category

First, we need to get the unique ID for the "General" category by querying your WordPress site's categories. Here's how to do that:

// Initialize your WordPress client with your site details
WordpressClient client = new WordpressClient("your-wordpress-site-url", "admin-username", "admin-password");

// Retrieve all categories from your site
List<Category> siteCategories = client.getCategories();
Long generalCategoryId = null;

// Loop through categories to find the "General" one
for (Category category : siteCategories) {
    if ("General".equalsIgnoreCase(category.getName())) {
        generalCategoryId = category.getId();
        break;
    }
}

// Handle the case where the category doesn't exist
if (generalCategoryId == null) {
    throw new RuntimeException("Oops! The 'General' category wasn't found on your WordPress site.");
}

Step 2: Create and Publish the Post with the Target Category

Once you have the category ID, you can create your post, attach the category, and publish it:

// Create a new Post object
Post newPost = new Post();

// Set basic post details
newPost.setTitle("My Awesome Post");
newPost.setContent("This is the full content of my post - feel free to add HTML here too!");
newPost.setStatus(PostStatus.PUBLISH); // Use PostStatus.DRAFT if you want to save without publishing

// Attach the "General" category using its ID
newPost.setCategories(Collections.singletonList(generalCategoryId));

// Publish the post to your WordPress site
Post publishedPost = client.createPost(newPost);

// Confirm success (optional)
System.out.println("Post published! Post ID: " + publishedPost.getId());
System.out.println("View it here: " + publishedPost.getLink());

Quick Notes to Keep in Mind

  • Permissions: Make sure the WordPress user you're using has the necessary permissions to publish posts and access category data.
  • Multiple Categories: If you want to assign the post to multiple categories, just add more IDs to the list passed to setCategories().
  • Error Handling: Wrap your code in try-catch blocks to handle common issues like network errors, invalid credentials, or missing categories.

内容的提问来源于stack exchange,提问作者Seomat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:44:09