Outside Query Loop
-
After spending WEEKS trying to do the most simple thing in WordPress I could imagine, I still failed and now I write here.
I am using the latest WordPress version (6.2) right now. As I understand, full site editor is a modern way to create pages today. I studied theme “twentytwentythree” and I came into conclusion , that “patterns” folder is the only place where I can write custom PHP code (and I want to write custom PHP code).
What have I done: I created custom post type (inside plugin, but that is irrelevant now) called “objectonmap”. Then I created custom fields for that custom post type using “metaboxes”. Fields are “lat” and “lon”. It worked! I was able to create new custom posts, fill custom fields and all of this was saved in DB, indeed! May be WordPress is not that horrific as I thought earlier? Now I want to output those new fields on an actual page. Right now I have only “index.html” inside “templates” folder. I used “WordPress Site Editor” to edit “Index” template. I added “Query Loop” using “Block Inserter” and selected “objectonmap” post type in “settings”. It worked! I was able to see a list of “objectonmap”, their “title” and “excerpt”.
Now I want to see “lat” and “lon” fields. Since I don’t want to just output their values, but in the future I want to draw a map, I created custom part “coordinates.html” inside “parts”. Inside was only this:
<!-- wp:pattern {"slug":"objectsonmap/coordinates"} /-->
Then I created “coordinates.php” file inside “patterns” folder. For testing purposes I included only echo “Hello, world” there. Then I opened “WordPress Site Editor” and added newly created “coordinates” block inside existing “Query Loop” block in “Index” template. Again, it worked! I can see “Hello, world” next to every “objectonmap” post on a page.
Real problem starts here. There is no way I can access post ID inside my custom pattern! I am supposed to be inside “Query Loop”, because I placed my block inside it, but I am not. “in_the_loop()” returns false. “global $wp_query; $wp_query->post” returns null. “get_post_meta” function do return what I want, but only if I provide the correct post ID, which I cannot get no matter what I do! Also tried “get_queried_object_id()” and “get_post()” functions with no success.
So what I am doing wrong? Why I am outside “Query Loop”?
- The topic ‘Outside Query Loop’ is closed to new replies.