Advertisement
Guest User

WordPress Dynamically create menu items from pages

a guest
Jan 5th, 2017
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.32 KB | None | 0 0
  1. function born_to_be_page() {
  2.     if(get_page_by_title('Page Title') == NULL ) {
  3.         parent_page('Page Title');
  4.     }
  5.     if(get_page_by_title('Page Child') == NULL ) {
  6.         child_page('Page Child');
  7.     }
  8. }
  9. add_action('init','born_to_be_page');
  10.  
  11. function parent_page($pageName) {
  12.     $createParentPage = array(
  13.         'post_title'    => $pageName,
  14.         'post_content'  => 'Some Content',
  15.         'post_status'   => 'publish',
  16.         'post_type'     => 'page',
  17.         'post_name'     => sanitize_title($pageName)
  18.     );
  19.     // Insert the post into the database
  20.     $parentPage = wp_insert_post($createParentPage);
  21.  
  22.     wp_update_nav_menu_item(get_term_by('slug', 'primary', 'nav_menu' )->term_id, 0, [
  23.         'menu-item-object-id' => $parentPage,
  24.         'menu-item-type' => 'post_type',
  25.         'menu-item-object' => 'page',
  26.         'menu-item-status' => 'publish'
  27.     ]);
  28. }
  29.  
  30. function child_page($pageName) {
  31.     $createChildPage = array(
  32.         'post_title'    => $pageName,
  33.         'post_content'  => 'Some Content',
  34.         'post_status'   => 'publish',
  35.         'post_author'   => 1,
  36.         'post_type'     => 'page',
  37.         'post_parent'   => 158,
  38.         'post_name'     => sanitize_title($pageName)
  39.     );
  40.     // Insert the post into the database
  41.     wp_insert_post($createChildPage);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement