WordPress.org

Ready to get started?Download WordPress

Forums

Blog ID always returns 1 (10 posts)

  1. duncmorley
    Member
    Posted 2 years ago #

    Hi

    I have a multisite set up and have a function in my functions.php file. I am using the following code to try and get the current blog ID:

    global $current_blog;
    switch_to_blog( $current_blog->blog_id; );

    For some reason the blog ID is always returning 1. If I hard code in the ID as 2, everything works fine but I need this to work dynamically.

    Does anyone have any suggestions??

  2. eugenealegiojo
    Member
    Posted 2 years ago #

    If I remember it correctly, WP developers have some discussions on the site id that always return to 1 for some reason.

    Have you tried using $blog_id as global?

  3. duncmorley
    Member
    Posted 2 years ago #

    Yes I have. Still can't figure this out.

  4. You can get the current blog id:

    <?php
    global $blog_id;
    if ($blog_id == 1) {
       //do something
    } else {
       //do something else
    }
    ?>

    Works fine.

  5. duncmorley
    Member
    Posted 2 years ago #

    Yeah, that works for me too, but the function I am using is within the functions.php file in a parent theme. See code below:

    [Code moderated as per the Forum Rules. The maximum number of lines of code that you can post in these forums is ten lines. Please use the pastebin]

  6. switch_to_blog($blog_id);

    Uh. At the risk of not understanding it, why are you saying 'Get the ID of the blog I'm on, and the SWITCH to that blog ID'?

  7. duncmorley
    Member
    Posted 2 years ago #

    Because it always returns 1. When I hard code the switch to an ID of 2 it displays the correct content, which is why I was looking for a way for the function to pick up the blog ID I am viewing.

  8. Where are you putting this code? I get the feeling I'm missing something really obvious that solves everything :)

  9. duncmorley
    Member
    Posted 2 years ago #

    I have a multisite setup. I am using a parent theme for all the sites with my set up. I have set up a 'product selector' widget within my parent theme that retrieves parent and child pages using AJAX.

    The first drop down within my product selector gets the parent pages, then retrieves the child pages based on the ID of the parent page. The function within my functions.php (in the parent theme) file is used to retrieve the child pages but because the blog_id always returns 1 it is never finding the correct child pages for the correct website/blog.

  10. Tim Moore
    Moderator
    Posted 2 years ago #

    Try using:

    global $wpdb;
    switch_to_blog( $wpdb->blogid );
    ...
    restore_current_blog();

Topic Closed

This topic has been closed to new replies.

About this Topic