Display category names on edit user profile using $wpdb

admin2025-06-03  4

On the 'Edit Profile' page I'm trying to loop through all the category names using $wpdb. Here is my code

<?php
function custom_user_profile_fields($profileuser) {
?>
<h1>Select a Category</h1>
<select name="category">
  <?php
    global $wpdb;
    $terms = $wpdb->query( "SELECT name FROM wp_terms" );
    foreach ( $terms as $term ) { ?>
      <option value=""><?php echo $term; ?></option>
    <?php }
  ?>
</select>
<?php
}
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');

But I'm getting empty option filed.

On the 'Edit Profile' page I'm trying to loop through all the category names using $wpdb. Here is my code

<?php
function custom_user_profile_fields($profileuser) {
?>
<h1>Select a Category</h1>
<select name="category">
  <?php
    global $wpdb;
    $terms = $wpdb->query( "SELECT name FROM wp_terms" );
    foreach ( $terms as $term ) { ?>
      <option value=""><?php echo $term; ?></option>
    <?php }
  ?>
</select>
<?php
}
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');

But I'm getting empty option filed.

Share Improve this question asked Feb 16, 2019 at 10:41 ShihabShihab 1341 gold badge3 silver badges11 bronze badges 8
  • use inbuilt wp_dropdown_categories [codex.wordpress/Function_Reference/wp_dropdown_categories] function . It would be the better option than $wpdb SQL query – Chinmoy Kumar Paul Commented Feb 16, 2019 at 11:11
  • Thanks for your kind reply. Previously I have done this using get_terms but I really need this using $wpdb for a specific reason. – Shihab Commented Feb 16, 2019 at 11:16
  • try $wpdb->get_results instead of $wpdb->query . Hopefully it would work. – Chinmoy Kumar Paul Commented Feb 16, 2019 at 11:23
  • Thank you so much! Though got a fatal error but at least I got few text which is really helpful. – Shihab Commented Feb 16, 2019 at 11:28
  • 1 "I really need this using $wpdb for a specific reason" What reason? – Jacob Peattie Commented Feb 16, 2019 at 11:53
 |  Show 3 more comments

1 Answer 1

Reset to default 1

The $wpdb->query() method doesn't return query results but a count on how many rows were affected by the query. To get the results you have to user the $wpdb->get_results($sqlString) method and then iterate over it.

<?php
function custom_user_profile_fields($profileuser) {
?>
<h1>Select a Category</h1>
<select name="category">
  <?php
    global $wpdb;
    $terms = $wpdb->get_results( "SELECT name FROM wp_terms" );
    foreach ( $terms as $term ) { ?>
      <option value=""><?php echo $term->name; ?></option>
    <?php }
  ?>
</select>
<?php
}
add_action('show_user_profile', 'custom_user_profile_fields');
add_action('edit_user_profile', 'custom_user_profile_fields');

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748900765a314662.html

最新回复(0)