Show and paginate only child categories with wordpress query
The real problem here is that you are querying in loops (almost always a bad pattern) because you are relying on built-in Wordpress querying functions, rather than writing raw SQL to query all this data at once.

My guess is you can do a single query to get both the paginated results and the total number of rows without limit being applied (by using SQL_CALC_FOUND_ROWS).

You might consider opening StackOverflow question specifically about the multiple/slow query problems along with information on your database tables relevant to these queries to get a suggestion on how to write an appropriate query.



Outside of that, I find your code incredibly difficult to read, and while some of that might have to do with following style conventions in Wordpress (which really bad IMO), you should at least indent you code and place comments properly (i.e. not prepending comment on code lines).