have_posts() in a function

Hi. I want to include json-ld on homepage and post page. This is the code:

<?php

function post_thins_in_footer() {
    
    global $wp_query;

    if ( is_single() ) {
        
        if ( have_posts() ) {
            ?>
            <script type="application/ld+json">
            <?php
                while ( have_posts() ) { the_post();
                    ?>
                    "@context": "https://schema.org"
                    etc
                    <?php
                }
            ?>
            </script>
            <?php
        }  
        
    }


    if ( is_home() ) {
        
        if ( have_posts() ) {
            ?>
            <script type="application/ld+json">
            <?php
                while ( have_posts() ) { the_post();
                    ?>
                    "@context": "https://schema.org"
                    etc
                    <?php
                }
            ?>
            </script>
            <?php
        }  
        
    }
    
}
add_action( 'wp_footer', 'post_thins_in_footer' );

It works, but I’m not sure if it’s ok to use it in a theme that I want to upload on ThemeForest…

Is this code a reason for a hard rejection?

This is not ok. You should include all your custom scripts into a .js file and enqueue it using the “wp_enqueue_script()” function.

After doing that, make sure to test the theme using the Envato Theme Check plugin.

Good Luck!

2 Likes

Between these tags

<script type=“application/ld+json”></script>

, if is homepage/archives, will be displayed infos (title, date, excerpt) about all posts.

If is_singular(post/page/attachment), will be displayed infos about the current post.

I’m not an expert in programming, but isn’t impossible to get what i want, with what you suggested (“include all your custom scripts into a .js file”)?

The only solution is to include the json-ld script in or . This shouldn’t be a problem, other authors, also include their scripts in or . (i have checked)

My only concern is about the php code above.

Hope you’ll understand… my english level is: taz, the tasmanian devil.

Thank you.

I understand your concerns, but why not using a plugin to achieve that? This way you will be sure about the code from your theme. (I guess this will be for a ThemeForest theme? or for a personal website?)