自定义WordPress最新文章插件无法限制文章数量求助
Let's break down why your custom widget isn't limiting the number of posts as you expect—there are a few straightforward fixes needed in your code:
1. Incorrect Category Query Parameter
You’re using 'cat' => 'RECIPES' in your WP_Query args, but the cat parameter requires a category ID, not the category name or slug. If you want to target a category by its URL-friendly slug, use category_name instead:
'category_name' => 'recipes', // Replace with your category's actual slug (usually lowercase)
2. Invalid & Unnecessary Query Parameters
You’ve added parameters like found_posts, max_num_pages, and post_count to your query—these are not valid input parameters for WP_Query. They’re properties WordPress generates after running the query, so including them here does nothing but clutter your code. Remove them entirely; only posts_per_page controls how many posts are returned.
3. Ignoring the Widget's Number Setting
Right now, you’re hardcoding 'posts_per_page' => '5' instead of using the $number variable you pulled from the widget instance. Worse, your update function is forcing $instance['number'] = '5', which means any number the user enters in the widget settings gets overwritten. Fix both of these:
Update the Query Args to Use the Widget Setting
In your widget() function, replace the hardcoded 5 with the $number variable (cast to integer to avoid issues):
$args1 = array( 'category_name' => 'recipes', 'posts_per_page' => intval($number), // Use the user-selected number 'order' => 'DESC', 'orderby' => 'ID', );
Fix the Update Function to Respect User Input
Modify the update() function to save the user’s chosen number instead of forcing it to 5:
function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = strip_tags( $new_instance['title'] ); // Save the user's input as an integer $instance['number'] = intval($new_instance['number']); return $instance; }
Final Notes
- Double-check that the
category_namevalue matches your actual category slug (you can find this in WordPress Admin → Posts → Categories, under the "Slug" column). - Using
intval()ensures the number is treated as an integer, preventing unexpected behavior from string values.
After making these changes, your widget should correctly display the number of posts the user selects in the settings, and only pull posts from your target category.
内容的提问来源于stack exchange,提问作者tmgolf

