0

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.

  • use inbuilt wp_dropdown_categories [codex.wordpress.org/Function_Reference/wp_dropdown_categories] function . It would be the better option than $wpdb SQL query – Chinmoy Kumar Paul Feb 16 '19 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 Feb 16 '19 at 11:16
  • try $wpdb->get_results instead of $wpdb->query . Hopefully it would work. – Chinmoy Kumar Paul Feb 16 '19 at 11:23
  • Thank you so much! Though got a fatal error but at least I got few text which is really helpful. – shihab Feb 16 '19 at 11:28
  • 1
    "I really need this using $wpdb for a specific reason" What reason? – Jacob Peattie Feb 16 '19 at 11:53
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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.