My initial thought is that the issue is here:
$category = get_the_category();
If get_the_category()
is returning categories in reverse-hierarchical order, then you can do this to put them back in order:
$category = get_the_category();
$category = array_reverse( $category );
However, I’m confused by this:
But some times facebook is coming 1st then Social Media 2nd…
If it is only happening sometimes, and not always, then I suspect that there is an issue somewhere else.