Custom query using WP_Query is not working

Its not clear what the goal is here, but here are some suggestions:

  • In general, the pre_get_posts hook is not a good place to instantiate a secondary query to display HTML.

  • Your current setup will result in an infinite-loop, because when you instantiate WP_Query within the pre_get_posts callback, you will instantiate it recursively, until you reach the recursive limit with an error.

  • There are ways to instantiate a WP_Query within the pre_get_posts, by removing the callback after the first run, but I don’t think that’s what you’re after.

  • Remove this part from your function:

    if( is_home() && $query->is_main_query()){
        global $wp_query;
    

    and e.g. display the function in your home template instead. Note that $query is undefined in that line.

  • There’s also the handy get_template_part() if you want to resuse template partials.

  • You might also want to consider a proper function prefix, instead of my_, to avoid possible name collisions.

tech