get categories in wordpress only parent level 1
To get only parent level 1 categories in WordPress, you can use the get_categories function with the parent parameter set to 0. Here's an example:
$parent_categories = get_categories(array(
'parent' => 0,
'hide_empty' => false // Set to true to hide empty categories
));
foreach ($parent_categories as $category) {
echo $category->name . '<br>';
}
In this example, the get_categories function is called with an array of parameters. The parent parameter is set to 0 to retrieve only the categories that have no parent. The hide_empty parameter is set to false to include empty categories as well. Then, a foreach loop is used to iterate over the retrieved categories and display their names.
Note: This code can be placed in a WordPress template file or a custom plugin.
原文地址: https://www.cveoy.top/t/topic/i34k 著作权归作者所有。请勿转载和采集!