PHP MySQL WordPress menu

I am currently working on a WordPress site for a client. This client has many people that will be managing the content of the site. That being said, I want to have the main menu auto populate, and have only 1 level of child pages auto populate into a sub menu(drop down).

I started building this in PHP using MySQL(obviously because that’s what the site is using). I currently have the PHP script working pretty close to perfect, except for the fact that I have been stuck on figuring out how to setup a loop for the sub menu.

Read More

I am a little more than a beginner when it comes to PHP & MySQL, so I am sure that there are some things that I am doing that could be done cleaner.

Below you will find the PHP script that I have written. This script currently works perfect for the “main menu”, but as you can see, I do not have a loop for the “sub menu”. If you could please inform me on the best way to do what I am trying to attempt here, that would be great!

function mainMenu() {
// connect to mysql
$link = mysql_connect( 'localhost', 'db_user', 'db_password' );

// select the database
mysql_select_db('db_name', $link);

$mSql = "
        SELECT a.*,
          b.post_title AS sub_title,
          b.post_name AS sub_name
        FROM wp_posts AS a
          LEFT JOIN wp_posts AS b
            ON a.ID = b.post_parent
            AND a.post_type = b.post_type
        WHERE a.post_type='page'
          AND a.post_status='publish' AND a.post_parent=0
        GROUP BY a.ID
        ";

$mItems = mysql_query($mSql);

echo '<ul id="menu-main-nav" class="menu">';
while($mResults = mysql_fetch_assoc($mItems)){
  echo '<li>';
  echo '<a href="'.$mResults['post_name'].'">'.$mResults['post_title'].'</a>';

  if($mResults['sub_title'] && $mResults['sub_name'] != null){
    echo '<ul class="sub-menu">';
      echo '<li>';
        echo '<a href="'.$mResults['sub_name'].'">'.$mResults['sub_title'].'</a>';
      echo '</li>';
    echo '</ul>';
  }
  echo '</li>';

}
echo '</ul>';
}

Thank you in advance for any help that you might have!

-Tyler

Related posts

Leave a Reply

1 comment