Un utilisateur a demandĂ© 👇

Salut Ă  tous, dĂ©solĂ© si cela est couvert, googler pendant un certain temps. J’ai une question qui contient 3 types de messages personnalisĂ©s (“actualitĂ©s”, “exposants”, “intervenants”). Je souhaite afficher 6 messages au total et 2 types de messages personnalisĂ©s chacun, c’est-Ă -dire deux actualitĂ©s, deux exposants et deux confĂ©renciers. Actuellement si je prĂ©cise ‘posts_per_page’ => 6â€Č et seulement 1 article d’actualitĂ©, 1, 4 douches seront affichĂ©es. J’ai presque besoin de ‘posts_per_post_type’ si cela a du sens. Question ci-dessous, merci d’avance.

$args = array( 'post_type' => array('news', 'exhibitors', 'speakers'), 'posts_per_page' => 6, 'order' => 'DESC', 'orderby' => 'type',  'paged' => $paged, 'tax_query' => array(
                        array(
                            'taxonomy' => 'foebar',
                            'field' => 'slug',
                            'terms' => array( $post_slug ) 
                        )
                    ));

Ce sujet a été modifié il y a 1 an et 9 mois par.


(@vrandom)

il y a 1 an, 9 mois

Je ne pense pas que ce que vous voulez puisse ĂȘtre fait en une seule question.

Je vois deux façons possibles selon la façon dont vous voulez les résultats.

Si vous utilisez get_posts pour exĂ©cuter la requĂȘte, vous pouvez exĂ©cuter une requĂȘte pour chaque post_type, limiter post_per_page Ă  2, puis fusionner les trois tableaux de rĂ©sultats en un seul tableau et l’utiliser pour afficher les publications.

Si vous utilisez WP_Query pour exĂ©cuter la requĂȘte, comme premiĂšre option, exĂ©cutez une requĂȘte pour tous les messages_type, limitez post_per_page Ă  2, conservez une copie des messages. Ensuite, Ă©crivez une requĂȘte sur post__ en utilisant WP_Query en utilisant les postes occupĂ©s demandĂ©s.

J’espĂšre que cela aide.


(@ainsleyclark)

il y a 1 an, 9 mois

Bonjour @vrandom Merci beaucoup pour votre rĂ©ponse rapide. J’utilise actuellement l’application WP pour rĂ©pertorier les messages, j’avais Ă  l’origine ces questions comme des questions diffĂ©rentes, mais je pensais que je ne pouvais pas utiliser page par page. Comment afficher 2 publications de chaque type de publication personnalisĂ©e en utilisant Ă©galement une page ? Le code est ci-dessous, merci encore.

<?php 
	$post_slug=$post->post_name;
	$args = array( 'post_type' => array('news', 'exhibitors', 'speakers'), 'posts_per_page' => 2, 'order' => 'DESC', 'orderby' => 'type',  'paged' => $paged, 'tax_query' => array(
	    array(
	        'taxonomy' => 'foebar',
	        'field' => 'slug',
	        'terms' => array( $post_slug ) 
	    )
	));
	$loop = new WP_Query( $args );
	$speakerCounter = 0;
	$exhibitorCounter = 0;
	$columnwidth="col-lg-6";
	if ( have_posts() ) : 
	    while ( $loop->have_posts() ) : $loop->the_post(); 
	        $post_type = get_post_type( $post->ID );
	        if ($post_type == 'news') {
	            require( locate_template ('blocks/content-newsrow.php'));
	        }
	        if ($post_type == 'exhibitors') {
	            if ($exhibitorCounter == 0) {echo '<div class="row">';}
	                $exhibitorCounter++;
	                echo $exhibitorCounter;
	                require( locate_template ('blocks/content-exhibitor.php'));
	            if ($exhibitorCounter == 1) {echo '</div>';}
	        }
	        if ($post_type == 'speakers') { 
	            if ($speakerCounter == 0) {echo '<div class="row">';}
	                $speakerCounter++;
	                require( locate_template ('blocks/content-speaker.php'));
	            if ($speakerCounter == 1) {echo '</div>';}
	        } 
	    endwhile;
	else :
	    echo '<h3>No News</h3>';
	endif; 
	wp_reset_postdata(); 
	?>


(@vrandom)

il y a 1 an, 9 mois

Eh bien, c’est un tour (page).

J’Ă©tais en train de faire des tests.

J’ai essayĂ© de regrouper mes idĂ©es par annĂ©es au lieu de post_types. Je n’ai pas de types de publication personnalisĂ©s sur mon site de dĂ©veloppement. J’ai donc essayĂ© la mĂȘme idĂ©e, en obtenant 2 emplois pour chaque annĂ©e dans la liste des annĂ©es.

La pagination est le problĂšme. Chaque sous-thĂšme a des rĂ©sultats d’appel diffĂ©rents et si j’ai retirĂ© les vĂȘtements des filiales, j’ai posĂ© une derniĂšre question en excluant ces vĂȘtements – le rĂ©sultat n’est pas 2 par an (alias post_type)

Je ne pense pas que mes idées originales fonctionneront.

Je pense que vous aurez besoin d’une question trĂšs personnalisĂ©e pour accomplir cela. Pour tester si je peux obtenir la base de donnĂ©es pour exĂ©cuter la requĂȘte. J’ai Ă©crit une question qui renverrait un ensemble graduĂ© de 2 messages par an pour les messages de ma base de donnĂ©es.


SELECT wp_posts.id, wp_posts.post_date
FROM   wp_posts INNER JOIN (
  SELECT   GROUP_CONCAT(ID ORDER BY post_date DESC) grouped_id, year(post_date) as group_year
  FROM     wp_posts
  GROUP BY year(post_date)) group_max
  ON year(wp_posts.post_date) = group_max.group_year
     AND FIND_IN_SET(wp_posts.id, grouped_id) <=2
ORDER BY
  wp_posts.id, post_date DESC
LIMIT 18446744073709551610 OFFSET 0;

une limite doit ĂȘtre la valeur maximale possible, elle n’est pas utilisĂ©e car nous limitons dĂ©jĂ  le rĂ©sultat avec l’option find_in_set, mais le dĂ©calage est la pagination.

Je pense que cela peut ĂȘtre modifiĂ© pour obtenir une rĂ©cupĂ©ration basĂ©e sur post_type. Cela vous permettrait de crĂ©er une page, car cela renverrait les informations nĂ©cessaires au fonctionnement de la page.

Quelque chose comme,


$sql_result = $wpdb->get_results( $sql, OBJECT);
$sql_posts_total = $wpdb->get_var( "SELECT FOUND_ROWS();" );
$max_num_pages = ceil($sql_posts_total / $post_per_page);

Le $max_num_pages pourrait ĂȘtre utilisĂ© dans les fonctions above_posts_link et next_posts_link pour crĂ©er des liens de page.

Je dois sortir de la maison pendant quelques heures, mais je voulais m’arrĂȘter lĂ  oĂč j’en Ă©tais avec la question.

Je choisirai oĂč j’irai Ă  mon retour.


(@ainsleyclark)

il y a 1 an, 9 mois

Bonjour @vrandom

Merci encore pour votre réponse, je ne peux pas dire que je parle couramment SQL, donc je viens de recevoir votre réponse.

J’ai essayĂ© d’utiliser un compteur pour tous les types de publication, mais j’obtiens des rĂ©sultats fongiques, dont certains apparaissent sur diffĂ©rentes pages, etc.

Ce serait trĂšs gentil si vous pouviez m’aider ! Merci beaucoup.

                <?php 
                    $post_slug=$post->post_name;
                    $args = array( 'post_type' => array('news', 'exhibitors', 'speakers'), 'posts_per_page' => 6, 'order' => 'DESC', 'orderby' => 'type',  'paged' => $currpage, 'tax_query' => array(
                        array(
                            'taxonomy' => 'foebar',
                            'field' => 'slug',
                            'terms' => array( $post_slug ) 
                        )
                    ));
                    $loop = new WP_Query( $args );
                    $speakerCounter = 0;
                    $exhibitorCounter = 0;
                    $newsCounter = 0;
                    $columnwidth="col-lg-6";
                    if ( have_posts() ) : 
                        while ( $loop->have_posts() ) : $loop->the_post(); 
                            $post_type = get_post_type( $post->ID );
                            if ($post_type == 'news' && $newsCounter < 2) {
                                $newsCounter++;
                                require( locate_template ('blocks/content-newsrow.php'));
                            }
                            if ($post_type == 'exhibitors' && $exhibitorCounter < 2) {
                                if ($exhibitorCounter == 0) {
                                    echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                                    <span class="contentbrands__title type__weight--medium">Exhibitors for <?php echo $contentbrand; ?>:</span>
                                    </div></div>
                                    <?php echo '<div class="row">'; ?>
                                <?php }
                                    $exhibitorCounter++;
                                    require( locate_template ('blocks/content-exhibitor.php'));
                                if ($exhibitorCounter == 2) {echo '</div>';}
                            }
                            if ($post_type == 'speakers' && $speakerCounter < 2) { 
                                if ($speakerCounter == 0) {
                                    echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                                    <span class="contentbrands__title type__weight--medium">Experts for <?php echo $contentbrand; ?>:</span>
                                    </div></div>
                                    <?php echo '<div class="row">'; ?>
                                <?php }
                                    $speakerCounter++;
                                    require( locate_template ('blocks/content-speaker.php'));
                                if ($speakerCounter == 1) {echo '</div>';}
                            } 
                        endwhile;
                    else :
                        echo '<h3>No News</h3>';
                    endif; 
                wp_reset_postdata(); 
                ?>
            </div>
            <div class="col-4">
                <?php get_sidebar(); ?>
            </div>
            <div class="col-12 pagination">
                <?php   echo previous_posts_link( 'Previous Page', $loop->max_num_pages);
                        echo get_next_posts_link( 'Next Page', $loop->max_num_pages );
                ?>
            </div>
        </div><!-- End Row -->


(@vrandom)

il y a 1 an, 8 mois

Ok, je pense que j’ai trouvĂ© une solution.

J’ai dĂ» faire certaines choses d’une maniĂšre diffĂ©rente. J’ai crĂ©Ă© ma propre classe WP_Query (en Ă©tendant WP_Query) pour pouvoir exĂ©cuter directement une instruction sql. Je l’ai fait parce que j’avais beaucoup de mal Ă  essayer de tout faire fonctionner avec la requĂȘte wpdb->get_resutls.

La deuxiĂšme chose que je devais faire Ă©tait de copier la fonction “paginate_links”, car l’original gĂ©nĂ©rerait des liens basĂ©s sur le wp_query global au lieu de ma requĂȘte $loop. Je ne sais pas qui pensait que les gens ne voudraient pas de liaisons de classes WP_Query autres que la classe globale. Quoi qu’il en soit, c’est beaucoup de code bidon qui est inquiĂ©tant, mais il sert son objectif.

Pour que la page fonctionne, la variable “found_posts” doit ĂȘtre dĂ©finie dans la classe WP_Query. Normalement, cela exĂ©cute “SELECT FOUND_ROWS ()” contre le SQL, mais nous avons besoin d’une solution diffĂ©rente car nous limitons le nombre de rĂ©sultats finaux Ă  la variable $post_per_posttype. Nous devons donc exĂ©cuter la requĂȘte deux fois, une fois avec le paramĂštre maximum possible de $post_per_posttype pour obtenir les messages trouvĂ©s pour la requĂȘte. Principalement pour qu’une page fonctionne, nous devons transmettre pass_per_page et found_posts au WP_Query personnalisĂ©.

Ensuite, nous envoyons le sql final Ă  la classe WP_Query personnalisĂ©e et rĂ©cupĂ©rons l’objet WP_Query qui permet Ă  toutes les fonctions spĂ©ciales de fonctionner ($loop->have_posts(), $loop->the_post(), etc.)

Je suppose que ce modĂšle inclut l’utilisation de la variable globale $post.

attach(loc_template(‘blocks/content-newsrow.php’)); attach(template_location(‘blocks/content-displayitor.php’)); connect(loc_template(‘blocks/speaker-content.php’));

Ils devraient donc fonctionner tels quels.

J’ai eu beaucoup de plaisir Ă  rĂ©soudre le puzzle. 🙂

Bon, le code.


<?php

      class WP_Query_CustomSQL extends WP_Query
      {

         public function __construct( $sql="", $query = [] ) {
            if ( ! empty( $sql ) ) {
               $this->query( $sql , $query );
            }
         }

         public function query( $sql, $query = [] ) {
            $this->init();
            $this->query = $this->query_vars = wp_parse_args( $query );
            $this->request = $sql;
            return $this->get_posts();
         }

         function get_posts()
         {
            global $wpdb;

            $q = &$this->query_vars;

            $post_type = $q['post_type'];
            $this->posts = null;

            $this->posts = $wpdb->get_results($this->request);

            $this->found_posts = $q['found_posts'];

                $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );

            // Convert to WP_Post objects.
            if ($this->posts) {
               $this->posts = array_map('get_post', $this->posts);
            }

            if ( $this->posts ) {
               $this->post_count = count( $this->posts );

               $this->posts = array_map( 'get_post', $this->posts );

               if ( $q['cache_results'] )
                  update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);

               $this->post = reset( $this->posts );
            } else {
               $this->post_count = 0;
               $this->posts = array();
            }

            return $this->posts;
         }
      }

      function paginate_links_with_provided_wpquery( $args="", $wp_query) {
         global $wp_rewrite;

         // Setting up default values based on the current URL.
         $pagenum_link = html_entity_decode( get_pagenum_link() );
         $url_parts    = explode( '?', $pagenum_link );

         // Get max pages and current page out of the current query, if available.
         $total   = isset( $wp_query->max_num_pages ) ? $wp_query->max_num_pages : 1;

         $current = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;

         // Append the format placeholder to the base URL.
         $pagenum_link = trailingslashit( $url_parts[0] ) . '%_%';

         // URL base depends on permalink settings.
         $format  = $wp_rewrite->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';
         $format .= $wp_rewrite->using_permalinks() ? user_trailingslashit( $wp_rewrite->pagination_base . '/%#%', 'paged' ) : '?paged=%#%';

         $defaults = array(
            'base'               => $pagenum_link, // http://example.com/all_posts.php%_% : %_% is replaced by format (below)
            'format'             => $format, // ?page=%#% : %#% is replaced by the page number
            'total'              => $total,
            'current'            => $current,
            'aria_current'       => 'page',
            'show_all'           => false,
            'prev_next'          => true,
            'prev_text'          => __( '&laquo; Previous' ),
            'next_text'          => __( 'Next &raquo;' ),
            'end_size'           => 1,
            'mid_size'           => 2,
            'type'               => 'plain',
            'add_args'           => array(), // array of query args to add
            'add_fragment'       => '',
            'before_page_number' => '',
            'after_page_number'  => '',
         );

         $args = wp_parse_args( $args, $defaults );

         if ( ! is_array( $args['add_args'] ) ) {
            $args['add_args'] = array();
         }

         // Merge additional query vars found in the original URL into 'add_args' array.
         if ( isset( $url_parts[1] ) ) {
            // Find the format argument.
            $format = explode( '?', str_replace( '%_%', $args['format'], $args['base'] ) );
            $format_query = isset( $format[1] ) ? $format[1] : '';
            wp_parse_str( $format_query, $format_args );

            // Find the query args of the requested URL.
            wp_parse_str( $url_parts[1], $url_query_args );

            // Remove the format argument from the array of query arguments, to avoid overwriting custom format.
            foreach ( $format_args as $format_arg => $format_arg_value ) {
               unset( $url_query_args[ $format_arg ] );
            }

            $args['add_args'] = array_merge( $args['add_args'], urlencode_deep( $url_query_args ) );
         }

         // Who knows what else people pass in $args
         $total = (int) $args['total'];
         if ( $total < 2 ) {
            return;
         }
         $current  = (int) $args['current'];
         $end_size = (int) $args['end_size']; // Out of bounds?  Make it the default.
         if ( $end_size < 1 ) {
            $end_size = 1;
         }
         $mid_size = (int) $args['mid_size'];
         if ( $mid_size < 0 ) {
            $mid_size = 2;
         }
         $add_args = $args['add_args'];
         $r="";
         $page_links = array();
         $dots = false;

         if ( $args['prev_next'] && $current && 1 < $current ) :
            $link = str_replace( '%_%', 2 == $current ? '' : $args['format'], $args['base'] );
            $link = str_replace( '%#%', $current - 1, $link );
            if ( $add_args )
               $link = add_query_arg( $add_args, $link );
            $link .= $args['add_fragment'];

            /**
             * Filters the paginated links for the given archive pages.
             *
             * @since 3.0.0
             *
             * @param string $link The paginated link URL.
             */
            $page_links[] = '<a class="prev page-numbers" href="' . esc_url( apply_filters( 'paginate_links', $link ) ) . '">' . $args['prev_text'] . '</a>';
         endif;
         for ( $n = 1; $n <= $total; $n++ ) :
            if ( $n == $current ) :
               $page_links[] = "<span aria-current="" . esc_attr( $args["aria_current'] ) . "' class="page-numbers current">" . $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number'] . "</span>";
               $dots = true;
            else :
               if ( $args['show_all'] || ( $n <= $end_size || ( $current && $n >= $current - $mid_size && $n <= $current + $mid_size ) || $n > $total - $end_size ) ) :
                  $link = str_replace( '%_%', 1 == $n ? '' : $args['format'], $args['base'] );
                  $link = str_replace( '%#%', $n, $link );
                  if ( $add_args )
                     $link = add_query_arg( $add_args, $link );
                  $link .= $args['add_fragment'];

                  /** This filter is documented in wp-includes/general-template.php */
                  $page_links[] = "<a class="page-numbers" href="" . esc_url( apply_filters( "paginate_links', $link ) ) . "'>" . $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number'] . "</a>";
                  $dots = true;
               elseif ( $dots && ! $args['show_all'] ) :
                  $page_links[] = '<span class="page-numbers dots">' . __( '&hellip;' ) . '</span>';
                  $dots = false;
               endif;
            endif;
         endfor;
         if ( $args['prev_next'] && $current && $current < $total ) :
            $link = str_replace( '%_%', $args['format'], $args['base'] );
            $link = str_replace( '%#%', $current + 1, $link );
            if ( $add_args )
               $link = add_query_arg( $add_args, $link );
            $link .= $args['add_fragment'];

            /** This filter is documented in wp-includes/general-template.php */
            $page_links[] = '<a class="next page-numbers" href="' . esc_url( apply_filters( 'paginate_links', $link ) ) . '">' . $args['next_text'] . '</a>';
         endif;
         switch ( $args['type'] ) {
            case 'array' :
               return $page_links;

            case 'list' :
               $r .= "<ul class="page-numbers">nt<li>";
               $r .= join("</li>nt<li>", $page_links);
               $r .= "</li>n</ul>n";
               break;

            default :
               $r = join("n", $page_links);
               break;
         }
         return $r;
      }
        // ----------------------------------------------------

      $post_slug=$post->post_name;

        // number of post to show per each post_type
        $post_per_posttype = 2;

        // to query
      $sql ="SELECT wp_posts.*
         FROM   wp_posts INNER JOIN (
           SELECT GROUP_CONCAT(ID ORDER BY post_date DESC) grouped_id, post_type
           FROM wp_posts
            inner join wp_term_relationships on wp_term_relationships.object_id = wp_posts.id
            inner join wp_term_taxonomy on wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
            inner join wp_terms on wp_term_taxonomy.term_id = wp_terms.term_id
            where wp_term_taxonomy.taxonomy = 'category' and wp_terms.slug = '$post_slug'
            and post_type in ('news', 'exhibitors', 'speakers')
           GROUP BY post_type
           ) group_max
           ON wp_posts.post_type = group_max.post_type
             AND FIND_IN_SET(wp_posts.id, grouped_id) <=#post_per_posttype#
         ORDER BY
           wp_posts.id, post_type DESC
         LIMIT 18446744073709551610 OFFSET 0;";

      global $wpdb;
      // need to pass the max posts possible to the query as it would not be generated correctly
      $found_posts = $wpdb->query(str_replace('#post_per_posttype#', 18446744073709551610, $sql));

      // page_per_posts is for pagination (post_per_posttype * num_of_posttypes_in_query)
      $loop = new WP_Query_CustomSQL(str_replace('#post_per_posttype#', $post_per_posttype, $sql), array( 'posts_per_page' => $post_per_posttype * 3 , 'found_posts' => $found_posts));

      $speakerCounter = 0;
      $exhibitorCounter = 0;
      $columnwidth="col-lg-6";
      if ( $loop->have_posts() ) :
         while ( $loop->have_posts() ) : $loop->the_post();
            $post_type = get_post_type( $post->ID );
            if ($post_type == 'news' && $newsCounter < 2) {
               $newsCounter++;
               require( locate_template ('blocks/content-newsrow.php'));
               //echo $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
           }
           if ($post_type == 'exhibitors' && $exhibitorCounter < 2) {
               if ($exhibitorCounter == 0) {
                   echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                   <span class="contentbrands__title type__weight--medium">Exhibitors for <?php echo $contentbrand; ?>:</span>
                   </div></div>
                   <?php echo '<div class="row">'; ?>
               <?php }
                   $exhibitorCounter++;
                   require( locate_template ('blocks/content-exhibitor.php'));
                   //echo $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
               if ($exhibitorCounter == 2) {echo '</div>';}
           }
           if ($post_type == 'speakers' && $speakerCounter < 2) {
               if ($speakerCounter == 0) {
                   echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                   <span class="contentbrands__title type__weight--medium">Experts for <?php echo $contentbrand; ?>:</span>
                   </div></div>
                   <?php echo '<div class="row">'; ?>
               <?php }
                   $speakerCounter++;
                   require( locate_template ('blocks/content-speaker.php'));
                   //echo $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
               if ($speakerCounter == 1) {echo '</div>';}
           }
         endwhile;

         // Previous/next page navigation.
         $args = array(
            'prev_text'          => __( 'Previous page', 'twentysixteen' ),
            'next_text'          => __( 'Next page', 'twentysixteen' ),
            'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentysixteen' ) . ' </span>',
            'screen_reader_text' => __( 'Posts navigation' ),
            'type'               => 'plain'
         );

         // Set up paginated links.
         $links = paginate_links_with_provided_wpquery( $args , $loop);

         if ( $links ) {
            echo _navigation_markup( $links, 'pagination', $args['screen_reader_text'] );
         }
         ?>

         <?php
      else :
         echo '<h3>No News</h3>';
      endif;
      wp_reset_postdata();

?>


(@ainsleyclark)

il y a 1 an, 8 mois

Bonjour @vrandom

Wow, merci beaucoup pour tout cela, vous avez certainement eu beaucoup de mal Ă  regarder ça pour moi. Je n’aurais certainement pas les connaissances nĂ©cessaires pour penser Ă  quelque chose comme ça.

J’ai collĂ© votre classe d’extension dans les fonctions my.php et mis le code sql dans ma page -news.php. AprĂšs avoir changĂ© les prĂ©fixes de table dans la requĂȘte SQL, je suis confrontĂ© Ă  cette erreur :

Avis : index non spécifié : post_type à /wordpress/localhost/website/wp-content/themes/website_theme/functions.php à la ligne 1131

Je ne sais pas oĂč aller pour cela, merci encore.

// ----------------------------------------------------

$post_slug=$post->post_name;

// number of post to show per each post_type
$post_per_posttype = 2;

// to query
$sql ="SELECT foe_342fj29x2_posts.*
 FROM   foe_342fj29x2_posts INNER JOIN (
   SELECT GROUP_CONCAT(ID ORDER BY post_date DESC) grouped_id, post_type
   FROM foe_342fj29x2_posts
    inner join foe_342fj29x2_term_relationships on foe_342fj29x2_term_relationships.object_id = foe_342fj29x2_posts.id
    inner join foe_342fj29x2_term_taxonomy on foe_342fj29x2_term_relationships.term_taxonomy_id = foe_342fj29x2_term_taxonomy.term_taxonomy_id
    inner join foe_342fj29x2_terms on foe_342fj29x2_term_taxonomy.term_id = foe_342fj29x2_terms.term_id
    where foe_342fj29x2_term_taxonomy.taxonomy = 'category' and foe_342fj29x2_terms.slug = '$post_slug'
    and post_type in ('news', 'exhibitors', 'speakers')
   GROUP BY post_type
   ) group_max
   ON foe_342fj29x2_posts.post_type = group_max.post_type
     AND FIND_IN_SET(foe_342fj29x2_posts.id, grouped_id) <=#post_per_posttype#
 ORDER BY
 foe_342fj29x2_posts.id, post_type DESC
 LIMIT 18446744073709551610 OFFSET 0;";

global $wpdb;
// need to pass the max posts possible to the query as it would not be generated correctly
$found_posts = $wpdb->query(str_replace('#post_per_posttype#', 18446744073709551610, $sql));

// page_per_posts is for pagination (post_per_posttype * num_of_posttypes_in_query)
$loop = new WP_Query_CustomSQL(str_replace('#post_per_posttype#', $post_per_posttype, $sql), array( 'posts_per_page' => $post_per_posttype * 3 , 'found_posts' => $found_posts));

$speakerCounter = 0;
$exhibitorCounter = 0;
$columnwidth="col-lg-6";

if ( $loop->have_posts() ) :
 while ( $loop->have_posts() ) : $loop->the_post();
    $post_type = get_post_type( $post->ID );
    if ($post_type == 'news' && $newsCounter < 2) {
       $newsCounter++;
       require( locate_template ('blocks/content-newsrow.php'));
       echo $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
   }
   if ($post_type == 'exhibitors' && $exhibitorCounter < 2) {
       if ($exhibitorCounter == 0) {
           echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
           <span class="contentbrands__title type__weight--medium">Exhibitors for <?php echo $contentbrand; ?>:</span>
           </div></div>
           <?php echo '<div class="row">'; ?>
       <?php }
           $exhibitorCounter++;
           require( locate_template ('blocks/content-exhibitor.php'));
           //echo $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
       if ($exhibitorCounter == 2) {echo '</div>';}
   }
   if ($post_type == 'speakers' && $speakerCounter < 2) {
       if ($speakerCounter == 0) {
           echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
           <span class="contentbrands__title type__weight--medium">Experts for <?php echo $contentbrand; ?>:</span>
           </div></div>
           <?php echo '<div class="row">'; ?>
       <?php }
           $speakerCounter++;
           require( locate_template ('blocks/content-speaker.php'));
           //echo $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
       if ($speakerCounter == 1) {echo '</div>';}
   }
 endwhile;

 // Previous/next page navigation.
 $args = array(
    'prev_text'          => __( 'Previous page', 'twentysixteen' ),
    'next_text'          => __( 'Next page', 'twentysixteen' ),
    'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentysixteen' ) . ' </span>',
    'screen_reader_text' => __( 'Posts navigation' ),
    'type'               => 'plain'
 );

 // Set up paginated links.
 $links = paginate_links_with_provided_wpquery( $args , $loop);

 if ( $links ) {
    echo _navigation_markup( $links, 'pagination', $args['screen_reader_text'] );
 }
 ?>

 <?php
else :
 echo '<h3>No News</h3>';
endif;
wp_reset_postdata();

?>

Cette réponse a été modifiée il y a 1 an et 8 mois par.


(@ainsleyclark)

il y a 1 an, 8 mois

En creusant, lors de l’impression de cette variable $q, je trouve Array( [posts_per_page] => 6 [found_posts] => 0). En supposant que cela soit liĂ© aux emplois trouvĂ©s.


(@vrandom)

il y a 1 an, 8 mois

Bon, j’ai fait quelques modifications.

Le problÚme a été complÚtement repensé, ainsi que la façon dont il calculait le fonctionnement du téléavertisseur.

Essayez-le et dites-moi comment ça se passe.


<?php
	
		class WP_Query_CustomSQL extends WP_Query
		{

			public function __construct( $sql="", $query = [] ) {
				if ( ! empty( $sql ) ) {
					$this->query( $sql , $query );
				}
			}

			public function query( $sql, $query = [] ) {
				$this->init();
				//$this->query = $this->query_vars = array();
				$this->query = $this->query_vars = wp_parse_args( $query );
				$this->request = $sql;
				return $this->get_posts();
			}

			function get_posts()
			{
				global $wpdb;

				$q = &$this->query_vars;

				$post_type = $q['post_type'];
				$this->posts = null;

				$this->posts = $wpdb->get_results($this->request);

				$this->found_posts = $q['found_posts'];

				if (isset($q['posts_per_page'])) {
				    $this->max_num_pages = $q['max_num_pages'];
				} else {
				    $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
				}

				// Convert to WP_Post objects.
				if ($this->posts) {
					$this->posts = array_map('get_post', $this->posts);
				}

				if ( $this->posts ) {
					$this->post_count = count( $this->posts );

					$this->posts = array_map( 'get_post', $this->posts );

					if ( $q['cache_results'] )
						update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);

					$this->post = reset( $this->posts );
				} else {
					$this->post_count = 0;
					$this->posts = array();
				}

				return $this->posts;
			}
		}

		function paginate_links_with_provided_wpquery( $args="", $wp_query) {
			global $wp_rewrite;

			// Setting up default values based on the current URL.
			$pagenum_link = html_entity_decode( get_pagenum_link() );
			$url_parts    = explode( '?', $pagenum_link );

			// Get max pages and current page out of the current query, if available.
			$total   = isset( $wp_query->max_num_pages ) ? $wp_query->max_num_pages : 1;
			$current = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;

			// Append the format placeholder to the base URL.
			$pagenum_link = trailingslashit( $url_parts[0] ) . '%_%';

			// URL base depends on permalink settings.
			$format  = $wp_rewrite->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';
			$format .= $wp_rewrite->using_permalinks() ? user_trailingslashit( $wp_rewrite->pagination_base . '/%#%', 'paged' ) : '?paged=%#%';

			$defaults = array(
				'base'               => $pagenum_link, // http://example.com/all_posts.php%_% : %_% is replaced by format (below)
				'format'             => $format, // ?page=%#% : %#% is replaced by the page number
				'total'              => $total,
				'current'            => $current,
				'aria_current'       => 'page',
				'show_all'           => false,
				'prev_next'          => true,
				'prev_text'          => __( '&laquo; Previous' ),
				'next_text'          => __( 'Next &raquo;' ),
				'end_size'           => 1,
				'mid_size'           => 2,
				'type'               => 'plain',
				'add_args'           => array(), // array of query args to add
				'add_fragment'       => '',
				'before_page_number' => '',
				'after_page_number'  => '',
			);

			$args = wp_parse_args( $args, $defaults );

			if ( ! is_array( $args['add_args'] ) ) {
				$args['add_args'] = array();
			}

			// Merge additional query vars found in the original URL into 'add_args' array.
			if ( isset( $url_parts[1] ) ) {
				// Find the format argument.
				$format = explode( '?', str_replace( '%_%', $args['format'], $args['base'] ) );
				$format_query = isset( $format[1] ) ? $format[1] : '';
				wp_parse_str( $format_query, $format_args );

				// Find the query args of the requested URL.
				wp_parse_str( $url_parts[1], $url_query_args );

				// Remove the format argument from the array of query arguments, to avoid overwriting custom format.
				foreach ( $format_args as $format_arg => $format_arg_value ) {
					unset( $url_query_args[ $format_arg ] );
				}

				$args['add_args'] = array_merge( $args['add_args'], urlencode_deep( $url_query_args ) );
			}

			// Who knows what else people pass in $args
			$total = (int) $args['total'];
			if ( $total < 2 ) {
				return;
			}
			$current  = (int) $args['current'];
			$end_size = (int) $args['end_size']; // Out of bounds?  Make it the default.
			if ( $end_size < 1 ) {
				$end_size = 1;
			}
			$mid_size = (int) $args['mid_size'];
			if ( $mid_size < 0 ) {
				$mid_size = 2;
			}
			$add_args = $args['add_args'];
			$r="";
			$page_links = array();
			$dots = false;

			if ( $args['prev_next'] && $current && 1 < $current ) :
				$link = str_replace( '%_%', 2 == $current ? '' : $args['format'], $args['base'] );
				$link = str_replace( '%#%', $current - 1, $link );
				if ( $add_args )
					$link = add_query_arg( $add_args, $link );
				$link .= $args['add_fragment'];

				/**
				 * Filters the paginated links for the given archive pages.
				 *
				 * @since 3.0.0
				 *
				 * @param string $link The paginated link URL.
				 */
				$page_links[] = '<a class="prev page-numbers" href="' . esc_url( apply_filters( 'paginate_links', $link ) ) . '">' . $args['prev_text'] . '</a>';
			endif;
			for ( $n = 1; $n <= $total; $n++ ) :
				if ( $n == $current ) :
					$page_links[] = "<span aria-current="" . esc_attr( $args["aria_current'] ) . "' class="page-numbers current">" . $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number'] . "</span>";
					$dots = true;
				else :
					if ( $args['show_all'] || ( $n <= $end_size || ( $current && $n >= $current - $mid_size && $n <= $current + $mid_size ) || $n > $total - $end_size ) ) :
						$link = str_replace( '%_%', 1 == $n ? '' : $args['format'], $args['base'] );
						$link = str_replace( '%#%', $n, $link );
						if ( $add_args )
							$link = add_query_arg( $add_args, $link );
						$link .= $args['add_fragment'];

						/** This filter is documented in wp-includes/general-template.php */
						$page_links[] = "<a class="page-numbers" href="" . esc_url( apply_filters( "paginate_links', $link ) ) . "'>" . $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number'] . "</a>";
						$dots = true;
					elseif ( $dots && ! $args['show_all'] ) :
						$page_links[] = '<span class="page-numbers dots">' . __( '&hellip;' ) . '</span>';
						$dots = false;
					endif;
				endif;
			endfor;
			if ( $args['prev_next'] && $current && $current < $total ) :
				$link = str_replace( '%_%', $args['format'], $args['base'] );
				$link = str_replace( '%#%', $current + 1, $link );
				if ( $add_args )
					$link = add_query_arg( $add_args, $link );
				$link .= $args['add_fragment'];

				/** This filter is documented in wp-includes/general-template.php */
				$page_links[] = '<a class="next page-numbers" href="' . esc_url( apply_filters( 'paginate_links', $link ) ) . '">' . $args['next_text'] . '</a>';
			endif;
			switch ( $args['type'] ) {
				case 'array' :
					return $page_links;

				case 'list' :
					$r .= "<ul class="page-numbers">nt<li>";
					$r .= join("</li>nt<li>", $page_links);
					$r .= "</li>n</ul>n";
					break;

				default :
					$r = join("n", $page_links);
					break;
			}
			return $r;
		}
        // ----------------------------------------------------

		$post_slug='news'; //$post->post_name;

        $post_types = ['post1', 'post2', 'post3'];

        // number of post to show per each post_type
        $post_per_posttype = 2;

        $sql_offset = get_query_var('paged', 0);
        if ($sql_offset -1 > 0) {
            $sql_offset = ($sql_offset - 1) * $post_per_posttype;
        }

		// Make SQL Parts
        $joinTemplate = [];
        $whereTemplate = [];
        $whereTemplateAddon = [];

		foreach ($post_types as $post_type_key => $post_type) {

		    $joinTemplate[] = "left join 			 
                (select GROUP_CONCAT(id  order by post_date desc, id desc) as grouped_id, post_type from (
                      SELECT id, post_type, post_date
                      FROM wp_posts 
                        inner join wp_term_relationships on wp_term_relationships.object_id = id
                        inner join wp_term_taxonomy on wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
                        inner join wp_terms on wp_term_taxonomy.term_id = wp_terms.term_id
                        where wp_term_taxonomy.taxonomy = 'category' and wp_terms.slug = '$post_slug'
                       and post_type in ('$post_type')
                       and post_status="publish"
                       order by post_date desc, id desc
                       LIMIT 18446744073709551610 offset #sql_offset#
                      ) d$post_type_key
                     GROUP BY d$post_type_key.post_type) post_type_$post_type_key		 
                     ON primary_wp_posts.post_type = post_type_$post_type_key.post_type";

		    $whereTemplate[] = "primary_wp_posts.post_type = post_type_$post_type_key.post_type";

		    $whereTemplateAddon[] = "AND (FIND_IN_SET(primary_wp_posts.id, post_type_$post_type_key.grouped_id) <= $post_per_posttype and FIND_IN_SET(primary_wp_posts.id, post_type_$post_type_key.grouped_id) > 0)";

		}

		$sql_template = "select #sql_col# from wp_posts primary_wp_posts
			    #join_templates_0#
			    #join_templates_1#
			    #join_templates_2#
                where
                  ((#where_0# #where_addon_0#)
			    or
 			      (#where_1# #where_addon_1#)
			    or
 			      (#where_2# #where_addon_2#))
 			      #append#";

        // Assemble Queries
		$sqlQuerys['found_post_query'] = $sql_template;
		$sqlQuerys['wp_query'] = $sql_template;

		$found_posts_sql = $sql_template;
		foreach ($post_types as $post_type_key => $post_type) {

		    $sqlQuerys['found_post_query'] = str_replace("#sql_col#", 'count(primary_wp_posts.id)', $sqlQuerys['found_post_query']);
		    $sqlQuerys['found_post_query'] = str_replace("#append#", 'group by primary_wp_posts.post_type', $sqlQuerys['found_post_query']);
		    $sqlQuerys['found_post_query'] = str_replace("#where_addon_$post_type_key#", '', $sqlQuerys['found_post_query']);
		    $sqlQuerys['found_post_query'] = str_replace("#join_templates_$post_type_key#", str_replace("#sql_offset#", 0,  $joinTemplate[$post_type_key]), $sqlQuerys['found_post_query']);
		    $sqlQuerys['found_post_query'] = str_replace("#where_$post_type_key#", $whereTemplate[$post_type_key], $sqlQuerys['found_post_query']);

		    $sqlQuerys['wp_query'] = str_replace("#sql_col#", '*', $sqlQuerys['wp_query']);
		    $sqlQuerys['wp_query'] = str_replace("#append#", "", $sqlQuerys['wp_query']);
		    $sqlQuerys['wp_query'] = str_replace("#where_addon_$post_type_key#", $whereTemplateAddon[$post_type_key], $sqlQuerys['wp_query']);
		    $sqlQuerys['wp_query'] = str_replace("#join_templates_$post_type_key#", str_replace("#sql_offset#", $sql_offset,  $joinTemplate[$post_type_key]), $sqlQuerys['wp_query']);
		    $sqlQuerys['wp_query'] = str_replace("#where_$post_type_key#", $whereTemplate[$post_type_key], $sqlQuerys['wp_query']);
		}
        //
		global $wpdb;
		// need to pass the max posts possible to the query as it would not be generated correctly
		$page_count_per_post_type = $wpdb->get_results($sqlQuerys['found_post_query'], ARRAY_N);

		// get the largest page count on a page
		$largest_page_count_per_post_type = 0;
		$found_posts = 0;
		foreach ($page_count_per_post_type as $page_count) {
		    $largest_page_count_per_post_type = ($page_count[0] > $largest_page_count_per_post_type)? $page_count[0]:$largest_page_count_per_post_type;
		    $found_posts += $page_count[0];
		}

		// page_per_posts is for pagination (post_per_posttype * num_of_posttypes_in_query)
		$loop = new WP_Query_CustomSQL($sqlQuerys['wp_query'], array( 'posts_per_page' => $post_per_posttype * 3 , 'found_posts' => $found_posts, 'max_num_pages' => ceil( $largest_page_count_per_post_type / $post_per_posttype  )));

		// put the post in the order of the post_types array
		if ($loop->have_posts()) {

		    // make posts index by post_type
		    $tmpPosts = [];
            foreach ($loop->posts as $k => $v) {
                $tmpPosts[get_post_type( $v->ID )][] = $v;
            }

            // assemble new ordered posts
            $finPosts = [];
            foreach ($post_types as $k => $v) {
                if (isset($tmpPosts[$v])) {
                    foreach ($tmpPosts[$v] as $k1 => $v2) {
                        $finPosts[] = $v2;
                    }
                }
            }

            // update the $loop with the new ordered posts
            $loop->posts = $finPosts;
		}

		$speakerCounter = 0;
		$exhibitorCounter = 0;
		$columnwidth="col-lg-6";
		if ( $loop->have_posts() ) :
			while ( $loop->have_posts() ) : $loop->the_post();
				$post_type = get_post_type( $post->ID );

				 if ($post_type == 'post1' && $newsCounter < 2) {
                    $newsCounter++;
                    //require( locate_template ('blocks/content-newsrow.php'));
                    echo $post->ID . '] ' . $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
                }
                if ($post_type == 'post2' && $exhibitorCounter < 2) {
                    if ($exhibitorCounter == 0) {
                        echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                        <span class="contentbrands__title type__weight--medium">Exhibitors for <?php echo $contentbrand; ?>:</span>
                        </div></div>
                        <?php echo '<div class="row">'; ?>
                    <?php }
                        $exhibitorCounter++;
                        //require( locate_template ('blocks/content-exhibitor.php'));
                        echo $post->ID . '] ' . $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
                    if ($exhibitorCounter == 2) {echo '</div>';}
                }
                if ($post_type == 'post3' && $speakerCounter < 2) {
                    if ($speakerCounter == 0) {
                        echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                        <span class="contentbrands__title type__weight--medium">Experts for <?php echo $contentbrand; ?>:</span>
                        </div></div>
                        <?php echo '<div class="row">'; ?>
                    <?php }
                        $speakerCounter++;
                        //require( locate_template ('blocks/content-speaker.php'));
                        echo $post->ID . '] ' . $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
                    if ($speakerCounter == 1) {echo '</div>';}
                }

			endwhile;

			// Previous/next page navigation.
			$args = array(
				'prev_text'          => __( 'Previous page', 'twentysixteen' ),
				'next_text'          => __( 'Next page', 'twentysixteen' ),
				'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentysixteen' ) . ' </span>',
				'screen_reader_text' => __( 'Posts navigation' ),
				'type'               => 'plain'
			);

			// Set up paginated links.
			$links = paginate_links_with_provided_wpquery( $args , $loop);

			if ( $links ) {
				echo _navigation_markup( $links, 'pagination', $args['screen_reader_text'] );
			}
			?>

			<?php
		else :
			echo '<h3>No News</h3>';
		endif;
		wp_reset_postdata();

?>


(@ainsleyclark)

il y a 1 an, 8 mois

Bonjour @vrandom

Merci encore pour votre réponse.

J’obtiens toujours la mĂȘme erreur. Attention : index non dĂ©fini : post_type


J’ai copiĂ© la classe dans functions.php et le reste dans ma page oĂč je veux afficher les messages. J’ai changĂ© tous les wp_ en prĂ©fixe de table, y compris primary_wp, pensez-vous que c’est correct ? J’ai aussi changĂ© mes types de travaux d’Ă©dition. Je ne sais pas s’il me manque quelque chose. Vous devriez certainement le faire dans un plugin quand il arrivera !

Code joint :

 // ----------------------------------------------------

 $post_slug='news'; //$post->post_name;

 $post_types = ['news', 'speakers', 'exhibitors'];

 // number of post to show per each post_type
 $post_per_posttype = 2;

 $sql_offset = get_query_var('paged', 0);
 if ($sql_offset -1 > 0) {
     $sql_offset = ($sql_offset - 1) * $post_per_posttype;
 }

 // Make SQL Parts
 $joinTemplate = [];
 $whereTemplate = [];
 $whereTemplateAddon = [];

 foreach ($post_types as $post_type_key => $post_type) {

     $joinTemplate[] = "left join 			 
         (select GROUP_CONCAT(id  order by post_date desc, id desc) as grouped_id, post_type from (
               SELECT id, post_type, post_date
               FROM foe_342fj29x2_posts 
                 inner join foe_342fj29x2_term_relationships on foe_342fj29x2_term_relationships.object_id = id
                 inner join foe_342fj29x2_term_taxonomy on foe_342fj29x2_term_relationships.term_taxonomy_id = foe_342fj29x2_term_taxonomy.term_taxonomy_id
                 inner join foe_342fj29x2_terms on foe_342fj29x2_term_taxonomy.term_id = foe_342fj29x2_terms.term_id
                 where foe_342fj29x2_term_taxonomy.taxonomy = 'category' and foe_342fj29x2_terms.slug = '$post_slug'
                and post_type in ('$post_type')
                and post_status="publish"
                order by post_date desc, id desc
                LIMIT 18446744073709551610 offset #sql_offset#
               ) d$post_type_key
              GROUP BY d$post_type_key.post_type) post_type_$post_type_key		 
              ON primary_foe_342fj29x2_posts.post_type = post_type_$post_type_key.post_type";

     $whereTemplate[] = "primary_foe_342fj29x2_posts.post_type = post_type_$post_type_key.post_type";

     $whereTemplateAddon[] = "AND (FIND_IN_SET(primary_foe_342fj29x2_posts.id, post_type_$post_type_key.grouped_id) <= $post_per_posttype and FIND_IN_SET(primary_foe_342fj29x2_posts.id, post_type_$post_type_key.grouped_id) > 0)";

 }

 $sql_template = "select #sql_col# from foe_342fj29x2_posts primary_foe_342fj29x2_posts
         #join_templates_0#
         #join_templates_1#
         #join_templates_2#
         where
           ((#where_0# #where_addon_0#)
         or
            (#where_1# #where_addon_1#)
         or
            (#where_2# #where_addon_2#))
            #append#";

 // Assemble Queries
 $sqlQuerys['found_post_query'] = $sql_template;
 $sqlQuerys['wp_query'] = $sql_template;

 $found_posts_sql = $sql_template;
 foreach ($post_types as $post_type_key => $post_type) {

     $sqlQuerys['found_post_query'] = str_replace("#sql_col#", 'count(primary_foe_342fj29x2_posts.id)', $sqlQuerys['found_post_query']);
     $sqlQuerys['found_post_query'] = str_replace("#append#", 'group by primary_foe_342fj29x2_posts.post_type', $sqlQuerys['found_post_query']);
     $sqlQuerys['found_post_query'] = str_replace("#where_addon_$post_type_key#", '', $sqlQuerys['found_post_query']);
     $sqlQuerys['found_post_query'] = str_replace("#join_templates_$post_type_key#", str_replace("#sql_offset#", 0,  $joinTemplate[$post_type_key]), $sqlQuerys['found_post_query']);
     $sqlQuerys['found_post_query'] = str_replace("#where_$post_type_key#", $whereTemplate[$post_type_key], $sqlQuerys['found_post_query']);

     $sqlQuerys['wp_query'] = str_replace("#sql_col#", '*', $sqlQuerys['wp_query']);
     $sqlQuerys['wp_query'] = str_replace("#append#", "", $sqlQuerys['wp_query']);
     $sqlQuerys['wp_query'] = str_replace("#where_addon_$post_type_key#", $whereTemplateAddon[$post_type_key], $sqlQuerys['wp_query']);
     $sqlQuerys['wp_query'] = str_replace("#join_templates_$post_type_key#", str_replace("#sql_offset#", $sql_offset,  $joinTemplate[$post_type_key]), $sqlQuerys['wp_query']);
     $sqlQuerys['wp_query'] = str_replace("#where_$post_type_key#", $whereTemplate[$post_type_key], $sqlQuerys['wp_query']);
 }
 //
 global $wpdb;
 // need to pass the max posts possible to the query as it would not be generated correctly
 $page_count_per_post_type = $wpdb->get_results($sqlQuerys['found_post_query'], ARRAY_N);

 // get the largest page count on a page
 $largest_page_count_per_post_type = 0;
 $found_posts = 0;
 foreach ($page_count_per_post_type as $page_count) {
     $largest_page_count_per_post_type = ($page_count[0] > $largest_page_count_per_post_type)? $page_count[0]:$largest_page_count_per_post_type;
     $found_posts += $page_count[0];
 }

 // page_per_posts is for pagination (post_per_posttype * num_of_posttypes_in_query)
 $loop = new WP_Query_CustomSQL($sqlQuerys['wp_query'], array( 'posts_per_page' => $post_per_posttype * 3 , 'found_posts' => $found_posts, 'max_num_pages' => ceil( $largest_page_count_per_post_type / $post_per_posttype  )));

 // put the post in the order of the post_types array
 if ($loop->have_posts()) {

     // make posts index by post_type
     $tmpPosts = [];
     foreach ($loop->posts as $k => $v) {
         $tmpPosts[get_post_type( $v->ID )][] = $v;
     }

     // assemble new ordered posts
     $finPosts = [];
     foreach ($post_types as $k => $v) {
         if (isset($tmpPosts[$v])) {
             foreach ($tmpPosts[$v] as $k1 => $v2) {
                 $finPosts[] = $v2;
             }
         }
     }

     // update the $loop with the new ordered posts
     $loop->posts = $finPosts;
 }

 $speakerCounter = 0;
 $exhibitorCounter = 0;
 $columnwidth="col-lg-6";
 if ( $loop->have_posts() ) :
     while ( $loop->have_posts() ) : $loop->the_post();
         $post_type = get_post_type( $post->ID );

          if ($post_type == 'post1' && $newsCounter < 2) {
             $newsCounter++;
             //require( locate_template ('blocks/content-newsrow.php'));
             echo $post->ID . '] ' . $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
         }
         if ($post_type == 'post2' && $exhibitorCounter < 2) {
             if ($exhibitorCounter == 0) {
                 echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                 <span class="contentbrands__title type__weight--medium">Exhibitors for <?php echo $contentbrand; ?>:</span>
                 </div></div>
                 <?php echo '<div class="row">'; ?>
             <?php }
                 $exhibitorCounter++;
                 //require( locate_template ('blocks/content-exhibitor.php'));
                 echo $post->ID . '] ' . $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
             if ($exhibitorCounter == 2) {echo '</div>';}
         }
         if ($post_type == 'post3' && $speakerCounter < 2) {
             if ($speakerCounter == 0) {
                 echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                 <span class="contentbrands__title type__weight--medium">Experts for <?php echo $contentbrand; ?>:</span>
                 </div></div>
                 <?php echo '<div class="row">'; ?>
             <?php }
                 $speakerCounter++;
                 //require( locate_template ('blocks/content-speaker.php'));
                 echo $post->ID . '] ' . $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
             if ($speakerCounter == 1) {echo '</div>';}
         }

     endwhile;

     // Previous/next page navigation.
     $args = array(
         'prev_text'          => __( 'Previous page', 'twentysixteen' ),
         'next_text'          => __( 'Next page', 'twentysixteen' ),
         'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentysixteen' ) . ' </span>',
         'screen_reader_text' => __( 'Posts navigation' ),
         'type'               => 'plain'
     );

     // Set up paginated links.
     $links = paginate_links_with_provided_wpquery( $args , $loop);

     if ( $links ) {
         echo _navigation_markup( $links, 'pagination', $args['screen_reader_text'] );
     }
     ?>

     <?php
 else :
     echo '<h3>No News</h3>';
 endif;
 wp_reset_postdata(); ?>


(@vrandom)

il y a 1 an, 8 mois

Hmm, je n’ai trouvĂ© qu’un seul endroit oĂč l’expression “post_type” est utilisĂ©e comme clĂ© d’index. Cependant, je ne sais pas pourquoi il ne fait pas d’erreur sur mon site de dĂ©veloppement.

Dans la classe WP_Query_CustomSQL, fonction get_post,


$q = &$this->query_vars;

$post_type = $q['post_type'];

change ça en


$q = &$this->query_vars;

$post_type="";
if (isset($q['post_type'])) {
    $post_type = $q['post_type'];
}


(@ainsleyclark)

il y a 1 an, 8 mois

Bonjour @vrandom

Pas encore de chance, le code ci-dessus a rĂ©ussi Ă  se dĂ©barrasser de l’erreur, mais aucun message n’est envoyĂ©, il ne produit donc rien.

Actuellement, la question concerne la taxonomie personnalisĂ©e, j’ajoute ce code avec un modĂšle de page pour toutes les pages de taxonomie. Je ne sais pas si c’est dĂ©jĂ  en place. Je ne sais pas non plus ce qui devrait ĂȘtre dans la variable post_slug en haut de la question. Peut-ĂȘtre que ça ne marche pas Ă  cause de ça ? je ne peux pas ĂȘtre sĂ»r

Ce serait formidable si cela pouvait fonctionner.

Merci encore.


$post_slug=$post->post_name;

$post_types = ['news', 'speakers', 'exhibitors'];

// number of post to show per each post_type
$post_per_posttype = 2;

$sql_offset = get_query_var('paged', 0);
if ($sql_offset -1 > 0) {
    $sql_offset = ($sql_offset - 1) * $post_per_posttype;
}

// Make SQL Parts
$joinTemplate = [];
$whereTemplate = [];
$whereTemplateAddon = [];

foreach ($post_types as $post_type_key => $post_type) {

    $joinTemplate[] = "left join 			 
        (select GROUP_CONCAT(id  order by post_date desc, id desc) as grouped_id, post_type from (
            SELECT id, post_type, post_date
            FROM foe_342fj29x2_posts 
                inner join foe_342fj29x2_term_relationships on foe_342fj29x2_term_relationships.object_id = id
                inner join foe_342fj29x2_term_taxonomy on foe_342fj29x2_term_relationships.term_taxonomy_id = foe_342fj29x2_term_taxonomy.term_taxonomy_id
                inner join foe_342fj29x2_terms on foe_342fj29x2_term_taxonomy.term_id = foe_342fj29x2_terms.term_id
                where foe_342fj29x2_term_taxonomy.taxonomy = 'category' and foe_342fj29x2_terms.slug = '$post_slug'
            and post_type in ('$post_type')
            and post_status="publish"
            order by post_date desc, id desc
            LIMIT 18446744073709551610 offset #sql_offset#
            ) d$post_type_key
            GROUP BY d$post_type_key.post_type) post_type_$post_type_key		 
            ON primary_foe_342fj29x2_posts.post_type = post_type_$post_type_key.post_type";

    $whereTemplate[] = "primary_foe_342fj29x2_posts.post_type = post_type_$post_type_key.post_type";

    $whereTemplateAddon[] = "AND (FIND_IN_SET(primary_foe_342fj29x2_posts.id, post_type_$post_type_key.grouped_id) <= $post_per_posttype and FIND_IN_SET(primary_foe_342fj29x2_posts.id, post_type_$post_type_key.grouped_id) > 0)";

}

$sql_template = "select #sql_col# from foe_342fj29x2_posts primary_foe_342fj29x2_posts
        #join_templates_0#
        #join_templates_1#
        #join_templates_2#
        where
        ((#where_0# #where_addon_0#)
        or
        (#where_1# #where_addon_1#)
        or
        (#where_2# #where_addon_2#))
        #append#";

// Assemble Queries
$sqlQuerys['found_post_query'] = $sql_template;
$sqlQuerys['wp_query'] = $sql_template;

$found_posts_sql = $sql_template;
foreach ($post_types as $post_type_key => $post_type) {

    $sqlQuerys['found_post_query'] = str_replace("#sql_col#", 'count(primary_foe_342fj29x2_posts.id)', $sqlQuerys['found_post_query']);
    $sqlQuerys['found_post_query'] = str_replace("#append#", 'group by primary_foe_342fj29x2_posts.post_type', $sqlQuerys['found_post_query']);
    $sqlQuerys['found_post_query'] = str_replace("#where_addon_$post_type_key#", '', $sqlQuerys['found_post_query']);
    $sqlQuerys['found_post_query'] = str_replace("#join_templates_$post_type_key#", str_replace("#sql_offset#", 0,  $joinTemplate[$post_type_key]), $sqlQuerys['found_post_query']);
    $sqlQuerys['found_post_query'] = str_replace("#where_$post_type_key#", $whereTemplate[$post_type_key], $sqlQuerys['found_post_query']);

    $sqlQuerys['wp_query'] = str_replace("#sql_col#", '*', $sqlQuerys['wp_query']);
    $sqlQuerys['wp_query'] = str_replace("#append#", "", $sqlQuerys['wp_query']);
    $sqlQuerys['wp_query'] = str_replace("#where_addon_$post_type_key#", $whereTemplateAddon[$post_type_key], $sqlQuerys['wp_query']);
    $sqlQuerys['wp_query'] = str_replace("#join_templates_$post_type_key#", str_replace("#sql_offset#", $sql_offset,  $joinTemplate[$post_type_key]), $sqlQuerys['wp_query']);
    $sqlQuerys['wp_query'] = str_replace("#where_$post_type_key#", $whereTemplate[$post_type_key], $sqlQuerys['wp_query']);
}
//
global $wpdb;
// need to pass the max posts possible to the query as it would not be generated correctly
$page_count_per_post_type = $wpdb->get_results($sqlQuerys['found_post_query'], ARRAY_N);

 // get the largest page count on a page
$largest_page_count_per_post_type = 0;
$found_posts = 0;
foreach ($page_count_per_post_type as $page_count) {
    $largest_page_count_per_post_type = ($page_count[0] > $largest_page_count_per_post_type)? $page_count[0]:$largest_page_count_per_post_type;
    $found_posts += $page_count[0];
}

// page_per_posts is for pagination (post_per_posttype * num_of_posttypes_in_query)
$loop = new WP_Query_CustomSQL($sqlQuerys['wp_query'], array( 'posts_per_page' => $post_per_posttype * 3 , 'found_posts' => $found_posts, 'max_num_pages' => ceil( $largest_page_count_per_post_type / $post_per_posttype  )));

// put the post in the order of the post_types array
if ($loop->have_posts()) {

    // make posts index by post_type
    $tmpPosts = [];
    foreach ($loop->posts as $k => $v) {
        $tmpPosts[get_post_type( $v->ID )][] = $v;
    }

    // assemble new ordered posts
    $finPosts = [];
    foreach ($post_types as $k => $v) {
        if (isset($tmpPosts[$v])) {
            foreach ($tmpPosts[$v] as $k1 => $v2) {
                $finPosts[] = $v2;
            }
        }
    }

    // update the $loop with the new ordered posts
    $loop->posts = $finPosts;
 }

 $speakerCounter = 0;
 $exhibitorCounter = 0;
 $columnwidth="col-lg-6";
 $post_type = get_post_type( $post->ID );
 if ( $loop->have_posts() ) :
     while ( $loop->have_posts() ) : $loop->the_post();

          if ($post_type == 'news' && $newsCounter < 2) {
             $newsCounter++;
             require( locate_template ('blocks/content-newsrow.php'));
             
             echo $post->ID . '] ' . $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
         }
         if ($post_type == 'exhibitors') {
             if ($exhibitorCounter == 0) {
                 echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                 <span class="contentbrands__title type__weight--medium">Exhibitors for <?php echo $contentbrand; ?>:</span>
                 </div></div>
                 <?php echo '<div class="row">'; ?>
             <?php }
                 $exhibitorCounter++;
                 require( locate_template ('blocks/content-exhibitor.php'));
                 echo $post->ID . '] ' . $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
             if ($exhibitorCounter == 2) {echo '</div>';}
         }
         if ($post_type == 'speakers') {
             if ($speakerCounter == 0) {
                 echo '<div class="row"><div class="col-12 mb-2 mb-lg-3">'; ?>
                 <span class="contentbrands__title type__weight--medium">Experts for <?php echo $contentbrand; ?>:</span>
                 </div></div>
                 <?php echo '<div class="row">'; ?>
             <?php }
                 $speakerCounter++;
                 require( locate_template ('blocks/content-speaker.php'));
                 echo $post->ID . '] ' . $post_type . ' - '  .  get_permalink($post->ID)  . "<BR>";
             if ($speakerCounter == 1) {echo '</div>';}
         }

     endwhile;

     // Previous/next page navigation.
     $args = array(
         'prev_text'          => __( 'Previous page', 'twentysixteen' ),
         'next_text'          => __( 'Next page', 'twentysixteen' ),
         'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentysixteen' ) . ' </span>',
         'screen_reader_text' => __( 'Posts navigation' ),
         'type'               => 'plain'
     );

     // Set up paginated links.
     $links = paginate_links_with_provided_wpquery( $args , $loop);

     if ( $links ) {
         echo _navigation_markup( $links, 'pagination', $args['screen_reader_text'] );
     }
     ?>

     <?php
 else :
     echo '<h3>No ss</h3>';
 endif;
 wp_reset_postdata(); ?>
business-leaders


(@vrandom)

il y a 1 an, 8 mois

C’est le code d’origine oĂč $post_slug a Ă©tĂ© utilisĂ©.


$post_slug=$post->post_name;
$args = array( 'post_type' => array('news', 'exhibitors', 'speakers'), 'posts_per_page' => 2, 'order' => 'DESC', 'orderby' => 'type',  'paged' => $paged, 'tax_query' => array(
	    array(
	        'taxonomy' => 'foebar',
	        'field' => 'slug',
	        'terms' => array( $post_slug ) 
	    )
	));

Il me semble étrange que $post->post_name soit utilisé pour un escargot de taxonomie.

C’est ce que j’ai dĂ©fini sur le dernier sql, mais je n’avais pas de taxonomie appelĂ©e foebar, j’ai donc utilisĂ© la catĂ©gorie. Je suppose que vous n’avez pas de taxonomie appelĂ©e foebar.

Avez-vous besoin de la partie tax_query ?


(@ainsleyclark)

il y a 1 an, 8 mois

Salut @vrandom,

Je dois avoir utilisĂ© $ post_slug pour renvoyer la taxonomie, le post slug et le slug de taxonomie ont la mĂȘme URL. La taxonomie s’appelle un foebar, et chacun a une page et un Im et en utilisant ce modĂšle de page pour chacun des 5, l’idĂ©e est que chaque page attirera des confĂ©renciers, des exposants et des nouvelles Ă©tiquetĂ©es avec la taxonomie particuliĂšre.

Dans la requĂȘte SQL, j’ai changĂ© “category” en escargot de courrier, mais je n’ai toujours pas renvoyĂ© de rĂ©sultats. Existe-t-il un moyen de tester la cause de la question SQL ?

Vous n’ĂȘtes pas sĂ»r Ă  100 % de votre tax_query ?

Merci beaucoup.

Cette réponse a été modifiée il y a 1 an et 8 mois par.


(@vrandom)

il y a 1 an, 8 mois

Vous avez donc crĂ©Ă© un type de taxonomie personnalisĂ© appelĂ© foobar et l’avez attachĂ© Ă  tous les types de publication personnalisĂ©s (‘actualitĂ©s’, ‘exposants’, ‘intervenants’).

Ok, placez ceci sous la ligne $post_slug = $post->post_name. Il devrait vider un enregistrement de la base de donnĂ©es en utilisant le type de publication “news”, une taxonomie personnalisĂ©e appelĂ©e “foobar” avec un escargot de valeur $page_slug.


global $wpdb;

$sql = "SELECT id, post_type, post_date
FROM foe_342fj29x2_posts 
inner join foe_342fj29x2_term_relationships on foe_342fj29x2_term_relationships.object_id = id
inner join foe_342fj29x2_term_taxonomy on foe_342fj29x2_term_relationships.term_taxonomy_id = foe_342fj29x2_term_taxonomy.term_taxonomy_id
inner join foe_342fj29x2_terms on foe_342fj29x2_term_taxonomy.term_id = foe_342fj29x2_terms.term_id
where 
foe_342fj29x2_term_taxonomy.taxonomy = 'foobar' and foe_342fj29x2_terms.slug = '$post_slug'
and post_type in ('news')
and post_status="publish"
order by post_date desc, id desc
limit 1 offset 0";
		
$results = $wpdb->get_results($sql);

echo "<pre>";
var_dump($results);
echo "</pre>";


(@ainsleyclark)

il y a 1 an, 8 mois

Bonjour @vrandom

Cela faisait Ă©cho Ă  ceci :

modifier (1) {
[0]=> objet (stdClass) # 6075 (3) {
[“id”]=> chaĂźne (3) “395”
[“post_type”]=> fil (4) « nouvelles »
[“post_date”]=> chaĂźne (19) “2019-02-24 09:36:45”}}

Cela a-t-il résolu votre problÚme ?

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *