Ajax button "Load more" is not loading correct language posts for loggedout user

  • Site ajax button “Load more” is not loading correct language version posts for logged out users. https://estg.oraxtech.com/en/realisations/ in this page when we click on load more button, Ajax Load more button is not getting correct language posts if we are logged out user. page is working correct for logged in user.

    Video of the issue is here : https://youtu.be/6asoV1biXk4

    archive-realisations.php

    <?php
    /**
     *
    * Template Name: Réalisations
     *
     * @package OxO
     * @subpackage OxO Template
     * @since OxO Template v1
     */
    $urlTemp = get_stylesheet_directory_uri();
    get_header();
    
    $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    
    $args = array (
          'post_type'              => 'realisations',
          'post_status'            => 'publish',
          'hide_empty'             => true,
          'posts_per_page'         => '9',
          'order'                  => 'ASC',
          'orderby'                => 'menu_order',
            'suppress_filters' => 0
    );
    
    $realisations = new WP_Query( $args );
    ?>
    
    <div class="oxo-view archive-realisations">
    
      <section class="sec_1 container bg-cream">
        <div class="wrapper">
          <div class="left">
            <div>
              <h2 class="heading--1 heading--dark"><?php echo get_field('titre', 'option'); ?></h2>
              <p><?php echo get_field('description', 'option'); ?></p>
            </div>
          </div>
          <div class="right sliderArchReal" data-index="1">
            <div class="img_wrap">
            <?php
                if ( $realisations->have_posts() ) {
                   while ( $realisations->have_posts() ){
                     $realisations->the_post();?>
                     <a class="image" href="<?php echo get_permalink(); ?>">
                       <div style="background-image: url(<?php echo get_field('image_bg')['url']; ?>)"></div>
                     </a>
              <?php
                }
              }?>
            </div>
    
              <div class="nav_box">
                <div class="text">
                <?php
                    if ( $realisations->have_posts() ) {
                       while ( $realisations->have_posts() ){
                         $realisations->the_post();?>
                    <div class="content">
                      <h4><?php echo get_field('titre_1'); ?></h4>
                      <p class="description"><?php echo get_field('titre_2'); ?></p>
                    </div>
                  <?php
                    }
                  }?>
                </div>
    
                <div class="arrow-wrap">
                  <svg class="arrow arrow-left" xmlns="https://www.w3.org/2000/svg" viewBox="0 0 10.36 13.97">
                    <defs><style>.arrow_cls-1{fill:none;stroke:#202022;stroke-miterlimit:10;}</style></defs>
                    <g id="arrow_Calque_2" data-name="Calque 2">
                      <g id="arrow_Layer_2" data-name="Layer 2">
                        <line class="arrow_cls-1" x1="5.18" x2="5.18" y2="12.7"/>
                        <polyline class="arrow_cls-1" points="9.98 7.78 5.18 13.22 0.38 7.78"/>
                      </g>
                    </g>
                  </svg>
                  <svg class="arrow arrow-right" xmlns="https://www.w3.org/2000/svg" viewBox="0 0 10.36 13.97">
                    <defs><style>.arrow_cls-1{fill:none;stroke:#202022;stroke-miterlimit:10;}</style></defs>
                    <g id="arrow_Calque_2" data-name="Calque 2">
                      <g id="arrow_Layer_2" data-name="Layer 2">
                        <line class="arrow_cls-1" x1="5.18" x2="5.18" y2="12.7"/>
                        <polyline class="arrow_cls-1" points="9.98 7.78 5.18 13.22 0.38 7.78"/>
                      </g>
                    </g>
                  </svg>
                </div>
              </div>
          </div>
        </div>
    
        <?php get_template_part( 'templates/template-part-bloc-arrow' ); ?>
        <?php get_template_part( 'templates/template-part-card' ); ?>
      </section>
    
      <section class="sec_2 container">
        <h3>
            <?php if(ICL_LANGUAGE_CODE=='en') { ?>
            <?php echo __('Our work', 'espresso'); ?>
            <?php } else { ?>
            <?php echo __('Réalisations', 'espresso'); ?>
            <?php } ?>
          </h3>
            
        <div class="line"></div>
        <div class="cat_wrap">
          <div class="cat<?php if (strpos($url,'?category=') == false) { echo ' active'; } ?>" data-cat="all" data-max="<?php $posts = get_posts('post_type=realisations&suppress_filters=0&posts_per_page=-1'); $count = count($posts); echo $count;?>">
            <?php if(ICL_LANGUAGE_CODE == "en") { ?>
              All services
            <?php }
            else { ?>
              Tous les services
            <?php } ?>
          </div>
    
          <?php
          $cat_maj = array(18,23,24);
          $args2 = array (
                'post_type'              => 'realisations',
                'post_status'            => 'publish',
                'hide_empty'             => true,
                'posts_per_page'         => '-1',
                'order'                  => 'ASC',
                'orderby'                => 'name',
                'include'                => $cat_maj,
                'suppress_filters' => 0
          );
          $cats1 = get_categories($args2);
    
          foreach($cats1 as $cat1) { ?>
    
          <div class="cat<?php if((strpos($url,'?category=') !== false) && ($_GET['category'] == $cat1->slug)) { echo ' active'; } ?>" data-cat="<?php echo $cat1->slug; ?>" data-max="<?php $posts = get_posts('post_type=realisations&suppress_filters=0&category_name='.$cat1->name.'&posts_per_page=-1'); $count = count($posts);echo $count;?>">
            <?php echo $cat1->name; ?>
          </div>
    
          <?php
             }
          ?>
    
          <div class="plus_wrap">
            <div class="plus_cat"><?php if(ICL_LANGUAGE_CODE == "en") { ?>More<?php } else { ?>Plus<?php } ?> <span>></span></div>
            <div class="plus_drop">
              <?php
              $cat_ex = array(1,18,23,24);
              $args3 = array (
                    'post_type'              => 'realisations',
                    'post_status'            => 'publish',
                    'hide_empty'             => true,
                    'posts_per_page'         => '-1',
                    'order'                  => 'ASC',
                    'orderby'                => 'name',
                    'exclude'                => $cat_ex,
                  'suppress_filters' => 0
              );
              $cats2 = get_categories($args3);
    
              foreach($cats2 as $cat2) { ?>
    
              <div class="cat<?php if((strpos($url,'?category=') !== false) && ($_GET['category'] == $cat2->slug)) { echo ' active'; } ?>" data-cat="<?php echo $cat2->slug; ?>" data-max="<?php $posts = get_posts('post_type=realisations&suppress_filters=0&category_name='.$cat2->name.'&posts_per_page=-1'); $count = count($posts);echo $count;?>">
                <?php echo $cat2->name; ?>
              </div>
    
              <?php
                 }
              ?>
            </div>
          </div>
    
        </div>
    
        <?php if (strpos($url,'?category=') !== false) {
            $slug = $_GET['category'];
            $args = array (
                  'post_type'              => 'realisations',
                  'category_name'          => $slug,
                  'post_status'            => 'publish',
                  'hide_empty'             => true,
                  'posts_per_page'         => '9',
                  'order'                  => 'ASC',
                  'orderby'                => 'menu_order',
                'suppress_filters' => 0
            );
    
            $realisationsPost = new WP_Query( $args );
          }
          else {
              $realisationsPost = $realisations;
          } ?>
    
          <div class="row project_wrap" data-anime="fade_box" data-total=<?php echo $realisationsPost->found_posts;?>>
    
          <?php  if ( $realisationsPost->have_posts() ) {
               while ( $realisationsPost->have_posts() ){
                 $realisationsPost->the_post();
                 $backgroundimage = get_field('thumbnail_image')['url'];
    				if(get_field('titre_1') == "undefined"){
    					continue;
    				}
                 if( !empty( $backgroundimage ) ):
                 ?>
                 <div class="col-4 project project-<?php echo get_the_ID(); ?>">
                   <a href="<?php echo get_permalink(); ?>">
                   <div class="project__image" style="background-image: url(<?php echo $backgroundimage ?>)"></div>
                   <div class="project__contenu">
                     <p class="title"><?php echo get_field('titre_1'); ?></p>
                     <p class="description"><?php echo get_field('titre_2'); ?></p>
                     <?php foreach((get_the_category()) as $category){ ?>
                     <p class="services"><?php echo $category->name; ?></p>
                   <?php } ?>
                     <p class="link"><?php echo get_field('texte_bouton_realisations', 'option'); ?> ></p>
                   </div>
                   </a>
                 </div>
            <?php endif;
              }
            }?>
    
        </div>
    
       <div id="open-btn" class="load_more btn" data-from=9 data-cat="all">
          <?php if(ICL_LANGUAGE_CODE == "en") { ?>
            Load More
          <?php }
          else { ?>
            Afficher plus
          <?php } ?>
        </div>
      </section>
    
    </div>
    
    <div id="overlay" class="close">
     
    </div>
    <script>
    
    jQuery(function($){
     $("#open-btn").click(function() {
        $("#overlay").fadeIn();
     $('#overlay').delay(500).fadeOut('slow');
      });
      
    
      
    });
    
    </script>
    
    <script> 
    /*jQuery(function($){
      jQuery(".load_more.btn").click(function() {
       jQuery("body.post-type-archive-realisations").addClass("overlay").fadeIn();
     jQuery('.overlay').delay(5000).fadeOut('slow').removeClass("overlay");
      });*/
      </script>
    
    <?php get_footer(); ?>

    Functions.php

    <?php
    
    function removeBlackRibbon() {
      show_admin_bar(false);
    }
    
    function addSupportTheme() {
      add_theme_support( 'menus' );
    }
    
    function ajax_filter_posts_scripts() {
      wp_enqueue_script( 'oxo_script', get_template_directory_uri() . '/dist/js/app.js', array('jquery') );
      wp_localize_script( 'oxo_script', 'ajax_url', admin_url('admin-ajax.php') );
    }
    add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
    
    register_nav_menus( array(
      'Top' => 'Navigation',
      'Bottom' => 'Navigation footer',
    ) );
    
    if( function_exists('acf_add_options_page') ) {
    	$args = array(
    		'page_title' => 'Global',
    		'menu_title' => 'Global',
    		'icon_url' => 'dashicons-warning',
    		'update_button'		=> __('Publier', 'acf'),
    		'position' => 9,
    		'post_id' => 'global'
      );
      acf_add_options_page($args);
    }
    
      if(function_exists('acf_add_options_page')) {
        $args = (array(
          'page_title'      => 'Page Réalisations', /* Use whatever title you want */
    
          'parent_slug'     => 'edit.php?post_type=realisations', /* Change "services" to fit your situation */
          'capability' => 'manage_options'
        ));
    
        acf_add_options_sub_page($args);
      }
    
    add_action( 'admin_menu', 'remove_default_post_type' );
    
    function remove_default_post_type() {
        remove_menu_page( 'edit.php' );
    }
    
    add_action( 'admin_bar_menu', 'remove_default_post_type_menu_bar', 999 );
    
    function remove_default_post_type_menu_bar( $wp_admin_bar ) {
        $wp_admin_bar->remove_node( 'new-post' );
    }
    
    add_action( 'wp_dashboard_setup', 'remove_draft_widget', 999 );
    
    function remove_draft_widget(){
        remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' );
    }
    
    function add_file_types_to_uploads($file_types){
    $new_filetypes = array();
    $new_filetypes['svg'] = 'image/svg+xml';
    $file_types = array_merge($file_types, $new_filetypes );
    return $file_types;
    }
    add_filter('upload_mimes', 'add_file_types_to_uploads');
    
    add_filter('acf/fields/post_object/query/name=event', 'post_object_options_filter', 10, 3);
    add_filter('acf/fields/post_object/query/name=prod', 'post_object_options_filter', 10, 3);
    
    function post_object_options_filter($options, $field, $the_post) {
    	$options['post_status'] = array('publish');
    	return $options;
    }
    
    add_action('init', 'create_post_type');
     function create_post_type() {
    
         register_post_type( 'realisations',
               array(
                   'labels' => array(
                       'name' => __( "Réalisations" ),
                       'singular_name' => __( "Réalisation" )
                   ),
      						 'public' => true,
      						 'show_ui' => true,
      						 'publicly_queryable' => true,
                   'has_archive' => true,
                   'menu_icon'   => 'dashicons-star-empty',
                   'taxonomies' => array( 'category' ),
                   'supports' => array( 'title', 'editor', 'custom-fields', 'page-attributes'),
               )
           );
    
           register_post_type( 'services',
                 array(
                     'labels' => array(
                         'name' => __( "Services" ),
                         'singular_name' => __( "service" )
                     ),
        						 'public' => true,
        						 'show_ui' => true,
        						 'publicly_queryable' => true,
                     'has_archive' => true,
                     'menu_icon'   => 'dashicons-clipboard',
                     'supports' => array( 'title', 'editor', 'custom-fields', 'page-attributes' ),
                 )
             );
    
           register_post_type( 'emplois',
                 array(
                     'labels' => array(
                         'name' => __( "Emplois" ),
                         'singular_name' => __( "Emplois" )
                     ),
                     'public' => true,
                     'show_ui' => true,
                     'publicly_queryable' => true,
                     'has_archive' => true,
                     'menu_icon'   => 'dashicons-businessman',
                     'taxonomies'  => array( 'category' ),
                     'supports' => array( 'title', 'editor', 'custom-fields', 'page-attributes' ),
                 )
             );
    }
    
    function custom_menu_order($menu_ord) {
        if (!$menu_ord) return true;
        return array(
         'index.php', // this represents the dashboard link
         'edit.php?post_type=page', // this is the default page menu
         'edit.php?post_type=services', // this is a custom post type menu
         'edit.php?post_type=realisations', // this is a custom post type menu
         'edit.php?post_type=emplois'
     );
    }
    add_filter('custom_menu_order', 'custom_menu_order');
    add_filter('menu_order', 'custom_menu_order');
    
    function myselector(){
        $languages = icl_get_languages('skip_missing=0');
    
        $items = "";
        if( ! empty( $languages ) ) {
            foreach( $languages as $l ){
                if( ! $l['active'] ) {
                    $items .= '<a class="lang_switch" href="' . $l['url'] . '">' . $l['language_code'] . '</a>';
                }
            }
        }
    
        return $items;
    }
    
    function count_posts($language_code = '', $post_type = 'post', $post_status = 'publish'){
    
      global $sitepress, $wpdb;
    
      //get default language code
      $default_language_code = $sitepress->get_default_language();
    
      //adjust post type to format WPML uses
      switch($post_type){
        case 'page':
          $post_type = 'post_page';
          break;
        case 'post':
          $post_type = 'post_post';
          break;
      }
    
      //are we dealing with originals or translations?
      $slc_param = $sitepress->get_default_language() == $language_code ? "IS NULL" : "= '{$default_language_code}'";
    
      $query = "SELECT COUNT( {$wpdb->prefix}posts.ID )
                                    FROM {$wpdb->prefix}posts
                                    LEFT JOIN {$wpdb->prefix}icl_translations ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}icl_translations.element_id
                                    WHERE {$wpdb->prefix}icl_translations.language_code = '{$language_code}'
                                    AND {$wpdb->prefix}icl_translations.source_language_code $slc_param
                                    AND {$wpdb->prefix}icl_translations.element_type = '{$post_type}'
                                    AND {$wpdb->prefix}posts.post_status = '$post_status'";
    
      return $wpdb->get_var( $query );
    }
    
    removeBlackRibbon();
    addSupportTheme();
    
    // Permet d'augmenter la taille des d'uploads dans le backend
    @ini_set( 'upload_max_size' , '200M' );
    @ini_set( 'post_max_size', '200M');
    @ini_set( 'max_execution_time', '300' );
    
    // RETINA SUPPORT
    
    add_filter( 'wp_generate_attachment_metadata', 'retina_support_attachment_meta', 10, 2 );
    /**
     * Retina images
     *
     * This function is attached to the 'wp_generate_attachment_metadata' filter hook.
     */
    function retina_support_attachment_meta( $metadata, $attachment_id ) {
        foreach ( $metadata as $key => $value ) {
            if ( is_array( $value ) ) {
                foreach ( $value as $image => $attr ) {
                    if ( is_array( $attr ) )
                        retina_support_create_images( get_attached_file( $attachment_id ), $attr['width'], $attr['height'], true );
                }
            }
        }
    
        return $metadata;
    }
    
    /**
     * Create retina-ready images
     *
     * Referenced via retina_support_attachment_meta().
     */
    function retina_support_create_images( $file, $width, $height, $crop = false ) {
        if ( $width || $height ) {
            $resized_file = wp_get_image_editor( $file );
            if ( ! is_wp_error( $resized_file ) ) {
                $filename = $resized_file->generate_filename( $width . 'x' . $height . '@2x' );
    
                $resized_file->resize( $width * 2, $height * 2, $crop );
                $resized_file->save( $filename );
    
                $info = $resized_file->get_size();
    
                return array(
                    'file' => wp_basename( $filename ),
                    'width' => $info['width'],
                    'height' => $info['height'],
                );
            }
        }
        return false;
    }
    
    add_filter( 'delete_attachment', 'delete_retina_support_images' );
    /**
     * Delete retina-ready images
     *
     * This function is attached to the 'delete_attachment' filter hook.
     */
    function delete_retina_support_images( $attachment_id ) {
        $meta = wp_get_attachment_metadata( $attachment_id );
        $upload_dir = wp_upload_dir();
        $path = pathinfo( $meta['file'] );
        foreach ( $meta as $key => $value ) {
            if ( 'sizes' === $key ) {
                foreach ( $value as $sizes => $size ) {
                    $original_filename = $upload_dir['basedir'] . '/' . $path['dirname'] . '/' . $size['file'];
                    $retina_filename = substr_replace( $original_filename, '@2x.', strrpos( $original_filename, '.' ), strlen( '.' ) );
                    if ( file_exists( $retina_filename ) )
                        unlink( $retina_filename );
                }
            }
        }
    }
    
    /////// END RETINA SUPPORT
    
    // add_filter( 'acf/load_value/key=group_5eb06b2b0697b', 'default_fields', 10, 3 );
    // function default_fields( $value, $post_id, $field ) {
    //
    //   // Only add default content for new posts
    //   if ( $value !== null ) {
    //     return $value;
    //   }
    //
    //   // Only add default content for certain post types
    //   // if ( ! in_array(
    // 	// 	get_post_type( $post_id ),
    // 	// 	array(
    // 	// 		@TODO Post Types
    // 	// 	) ) ) {
    // 	// 	return $value;
    // 	// }
    //
    //   // Set up your initial post, then get the field id's of the settings you want to set
    //   // They look like: field_5b4e57efd0660_field_5b4e63e479d81
    //   // Add them after the acf_fc_layout
    //   $value = array(
    //     array(
    //       'acf_fc_layout' => 'Intro',
    //       'field_5eb06b3b58049' => 'Default Value'
    //     ),
    //
    //   );
    //
    //   return $value;
    // }
    
    add_action('wp_ajax_ajax_filter_real_cat', 'ajax_filter_real_cat_callback');
    add_action('wp_ajax_nopriv_ajax_filter_real_cat', 'ajax_filter_real_cat_callback');
    
    function ajax_filter_real_cat_callback() {
      header("Content-Type: application/json");
    
      // WP Query
      if($_GET['cat'] == 'all') {
        $args = array(
          'post_type'              => 'realisations',
          'post_status'            => 'publish',
          'posts_per_page'         => '9',
          'order'                  => 'ASC',
          'orderby'                => 'menu_order',
        );
      }
      else {
        $args = array(
          'category_name'          => $_GET['cat'],
          'post_type'              => 'realisations',
          'post_status'            => 'publish',
          'posts_per_page'         => '9',
          'order'                  => 'ASC',
          'orderby'                => 'menu_order',
        );
      }
    
      $query = new WP_Query( $args );
    
      $i = 0;
    
      if ( $query->have_posts() ) :
        $result_list = array();
        while ( $query->have_posts() ) : $query->the_post();
        $category_list='';
          foreach((get_the_category()) as $category){
            $category_list .='<p class="services">'.$category->name.'</p>';
          }
          $result_list[$i]["lien"] = get_permalink();
          $result_list[$i]["img"] = get_field('thumbnail_image')['url'];
          // $result_list[$i]["img"] = get_field('image_bg')['url'];
          $result_list[$i]["titre1"] = get_field('titre_1');
          $result_list[$i]["titre2"] = get_field('titre_2');
          $result_list[$i]["cats"] = $category_list;
          $result_list[$i]["cta"] = get_field('texte_bouton_realisations', 'option');
          $i++;
    
        endwhile;
          wp_reset_query();
          $result = array ( $result_list);
          echo json_encode($result);
      else:
        $result = "No result";
        echo json_encode($result);
      endif;
      die();
    }
    
    add_action('wp_ajax_ajax_filter_real_load', 'ajax_filter_real_load_callback');
    add_action('wp_ajax_nopriv_ajax_filter_real_load', 'ajax_filter_real_load_callback');
    
    function ajax_filter_real_load_callback() {
      header("Content-Type: application/json");
    
      // WP Query
      if($_GET['cat'] == 'all') {
        $args = array(
          'post_type'              => 'realisations',
          'post_status'            => 'publish',
          'offset'                 => $_GET['offset'],
          'posts_per_page'         => $_GET['last'],
          'order'                  => 'ASC',
          'orderby'                => 'menu_order',
        );
      }
      else {
        $args = array(
          'category_name'          => $_GET['cat'],
          'post_type'              => 'realisations',
          'post_status'            => 'publish',
          'offset'                 => $_GET['offset'],
          'posts_per_page'         => $_GET['last'],
          'order'                  => 'ASC',
          'orderby'                => 'menu_order',
        );
      }
    
      $query = new WP_Query( $args );
    
      $i = 0;
    
      if ( $query->have_posts() ) :
        $result_list = array();
        while ( $query->have_posts() ) : $query->the_post();
        $category_list='';
          foreach((get_the_category()) as $category){
            $category_list .='<p class="services">'.$category->name.'</p>';
          }
          $result_list[$i]["lien"] = get_permalink();
          $result_list[$i]["img"] = get_field('thumbnail_image')['url'];
          // $result_list[$i]["img"] = get_field('image_bg')['url'];
          $result_list[$i]["titre1"] = get_field('titre_1');
          $result_list[$i]["titre2"] = get_field('titre_2');
          $result_list[$i]["cats"] = $category_list;
          $result_list[$i]["cta"] = get_field('texte_bouton_realisations', 'option');
          $i++;
    
        endwhile;
          wp_reset_query();
          $result = array ( $result_list);
          echo json_encode($result);
      else:
        $result = "No result";
        echo json_encode($result);
      endif;
      die();
    }
    

    App.js https://jsfiddle.net/waqas1/roLbhz26/ i have uploaded some code at jsfiddle

    The blog I need help with is: (visible only to logged in users)

  • Hey there, would you be willing to share this in the Advanced WordPress forum over here?
    https://wordpress.org/support/forum/wp-advanced/

    This forum is primarily for the free-tier sites we host, which don’t allow any outside code, so your question is a bit out of our wheelhouse. You may need to create an account at WordPress.org, but once you have that you’ll be set going forward.

    Also, for more info on the difference between our managed hosting services (ranging from free to VIP) and the free WordPress software, see this article:
    https://wordpress.com/go/website-building/wordpress-com-vs-wordpress-org/

  • The topic ‘Ajax button "Load more" is not loading correct language posts for loggedout user’ is closed to new replies.