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.

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

    $current_post_type = 'music';

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


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

                <div class="wrapper wrapper-archive flex-cols">
                    $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' );



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

                    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 ?>

Any comments about the code are welcome. Thanks.

1 Answer 1


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 and acknowledge you have read our privacy policy.

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