0

My website has two different page templates. Each page template contains a different custom post type. The posts from the loops can be loaded by AJAX to load more.

This is the common code that I run for the two template pages. It includes the loop and I use is_page_template() with PHP variables to detect which template is in the frontend to load the custom post type music or movies.

The thing is, my level of PHP is basic and I'm not sure if my code is secure or has any breach.

<?php
if( is_page_template( 'page-music.php' ) ) :

    $current_post_type = 'music';

elseif( is_page_template( 'page-movies.php' ) ) :
    
    $current_post_type = 'movies';

endif;
?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

                <div class="wrapper wrapper-archive flex-cols">
                    <?php
                    $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
                    $args = array(
                        'post_type' => $current_post_type,
                        'post_status' => 'publish',
                        'posts_per_page' => 4,
                        'paged' => $paged
                    );

                    $loop = new WP_Query( $args );
                    while ( $loop->have_posts() ) : $loop->the_post();

                        get_template_part( 'template-parts/content', 'cpt-archive' );

                    endwhile;

                    wp_reset_postdata();
                    ?>
                </div>

                <?php
                if ($loop->max_num_pages > 1) :
                    echo '<button id="load-more-'. $current_post_type .'" class="load-more-archive">Load more</button>';
                endif;
                ?>

                <script>
                    var current_post_type = '<?php echo $current_post_type ?>', 
                    posts_myajax = '<?php echo serialize( $loop->query_vars ) ?>',
                    current_page_myajax = 1,
                    max_page_myajax = <?php echo $loop->max_num_pages ?>
                </script>
                
    </article>

Any comments about the code are welcome. Thanks.

0

I have some recommendation maybe could help You and Other

  1. for better security and some reason create a plugin for do it and use shortcode or other way for print result in front page
  2. don't use ajax call to the direct php file and use admin_ajax.php which you can find how to use in wp document
  3. prevent direct access to php file with this code on the first line of all php files if(! defined( 'ABSPATH' )){die("You Can not Access Directly to This File")}
  4. Alwayse use wp-nonce for send and receive any data in wordpress

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.