WordPress: Query Posts by Keyword in Title - PHP Code Example
To query posts in WordPress by keyword name in the title, you can use the following code:
\
$args = array(\
'post_type' => 'post',\
's' => 'your_keyword',\
'posts_per_page' => -1,\
);\
\
$posts = new WP_Query($args);\
\
if ($posts->have_posts()) {\
while ($posts->have_posts()) {\
$posts->the_post();\
// Display post title or perform any other actions\
the_title();\
}\
} else {\
// No posts found\
}\
\
wp_reset_postdata();\
```\
\
Replace `'your_keyword'` with the actual keyword you want to search for in the post titles. This code creates a new `WP_Query` object with the specified arguments, including the keyword search parameter (`'s'`). It then loops through the found posts and displays the post title using `the_title()` function. Finally, `wp_reset_postdata()` is used to restore the global post data to its original state.\
\
Note: Make sure to place this code in an appropriate location within your WordPress theme or plugin files.
原文地址: https://www.cveoy.top/t/topic/p6p2 著作权归作者所有。请勿转载和采集!