Pregunta sobre Developing with WordPress de Wordpress:

Publicaciones por p谩gina -> Por tipo de publicaci贸n

Un usuario pregunt贸 馃憞

Hola a todos, lo siento si esto est谩 cubierto, buscando en Google por un tiempo. Tengo una pregunta que contiene 3 tipos de publicaciones personalizadas (‘noticias’, ‘expositores’, ‘oradores’). Quiero mostrar 6 publicaciones en total y 2 tipos de publicaciones personalizadas cada una, es decir, dos noticias, dos expositores y dos oradores. Actualmente, si especifico ‘posts_per_page’ => 6 鈥 y solo se mostrar谩n 1 art铆culo de noticias, 1, 4 duchas. Casi necesito ‘posts_per_post_type’ si eso tiene sentido. Pregunta a continuaci贸n, gracias de antemano.

$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 ) 
                        )
                    ));

Este tema fue modificado hace 1 a帽o, 9 meses por.

(@vrandom)

Hace 1 a帽o, 9 meses

No creo que lo que quieres se pueda hacer en una sola pregunta.

Veo dos formas posibles dependiendo de c贸mo quieras los resultados.

Si est谩 utilizando get_posts para ejecutar la consulta, puede ejecutar una consulta para cada post_type, limitar post_per_page a 2, luego fusionar las tres matrices de resultados en una matriz y usarla para mostrar las publicaciones .

Si est谩 utilizando WP_Query para ejecutar la consulta, como la primera opci贸n, ejecute una consulta para todos los posts_type, l铆mite de post_per_page a 2, guarde una copia de las publicaciones. Luego escriba una consulta sobre post__ usando WP_Query usando las posiciones retenidas solicitadas.

Espero que ayude.

(@ainsleyclark)

Hace 1 a帽o, 9 meses

Hola @vrandom Muchas gracias por tu r谩pida respuesta. Actualmente estoy usando la aplicaci贸n WP para enumerar las publicaciones, originalmente ten铆a estas preguntas como preguntas diferentes, pero pens茅 que no pod铆a usar p谩gina por p谩gina. 驴C贸mo visualizo 2 publicaciones de cada tipo de publicaci贸n personalizada usando una p谩gina tambi茅n? El c贸digo est谩 abajo, gracias de nuevo.

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

Hace 1 a帽o, 9 meses

Bien, eso es un giro (p谩gina).

Estaba realizando algunas pruebas.

Intent茅 agrupar mis ideas por a帽os en lugar de post_types. No tengo tipos de publicaciones personalizados en mi sitio de desarrollo. As铆 que intent茅 la misma idea, conseguir 2 trabajos para cada a帽o de la lista de a帽os.

La paginaci贸n es el problema. Cada subtema tiene diferentes resultados de llamadas y si quit茅 la ropa de las subsidiarias, hice una pregunta final excluyendo esa ropa: el resultado no es 2 por a帽o (tambi茅n conocido como post_type)

No creo que mis ideas originales funcionen.

Creo que necesitar谩 una pregunta muy personalizada para lograr esto. Para probar si puedo hacer que la base de datos ejecute la consulta. Escrib铆 una pregunta que devolver铆a un conjunto graduado de 2 publicaciones por a帽o para publicaciones en mi base de datos.


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;

se requiere un l铆mite para que sea el valor m谩ximo posible, no se usa porque ya estamos limitando el resultado con la opci贸n find_in_set, pero el offset es la paginaci贸n.

Creo que esto se puede modificar para obtener una recuperaci贸n basada en post_type. Esto le permitir铆a crear una p谩gina, ya que devolver铆a la informaci贸n necesaria para que la p谩gina funcione.

Algo como,


$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);

Los $ max_num_pages podr铆an usarse en las funciones_posts_link anteriores y next_posts_link para hacer los enlaces de la p谩gina.

Tengo que salir de casa unas horas, pero quer铆a pasar por donde estaba con la pregunta.

Elegir茅 d贸nde me ir茅 cuando regrese.

(@ainsleyclark)

Hace 1 a帽o, 9 meses

Hola @vrandom

Gracias de nuevo por tu respuesta, no puedo decir que domine SQL, as铆 que acabo de recibir tu respuesta.

Intent茅 usar un contador para todo tipo de publicaciones, pero obtengo resultados f煤ngicos, algunos de los cuales aparecen en diferentes p谩ginas, etc.

隆Ser铆a muy agradable si me pudieran ayudar! Muchas gracias.

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

Hace 1 a帽o, 8 meses

Bien, creo que llegu茅 a una soluci贸n.

Tuve que hacer algunas cosas de una manera diferente. Cre茅 mi propia clase WP_Query (ampliando WP_Query) para poder ejecutar una declaraci贸n sql directamente. Hice esto porque ten铆a mucho dolor al intentar que todo funcionara con la consulta wpdb-> get_resutls.

La segunda cosa que tuve que hacer fue copiar la funci贸n 芦paginate_links禄, ya que el original generar铆a enlaces basados 鈥嬧媏n el wp_query global en lugar de mi consulta $ loop. No estoy seguro de qui茅n pens贸 que la gente no querr铆a enlaces de clases de WP_Query que no fueran la global. De todos modos, es una gran cantidad de c贸digo enga帽oso lo que preocupa, pero cumple su prop贸sito.

Para que la p谩gina funcione, se debe establecer la variable 芦found_posts禄 en la clase WP_Query. Normalmente, esto ejecuta 芦SELECT FOUND_ROWS ()禄 contra el sql, pero necesitamos una soluci贸n diferente ya que estamos limitando el n煤mero de resultados finales a la var $ post_per_posttype. Por lo tanto, debemos ejecutar la consulta dos veces, una vez con la configuraci贸n m谩xima posible de $ post_per_posttype para obtener los mensajes encontrados para la consulta. Principalmente para que una p谩gina funcione, necesitamos reenviar pass_per_page y found_posts al WP_Query personalizado.

A continuaci贸n, enviamos el sql final a la clase personalizada WP_Query y recuperamos el objeto WP_Query que permite que todas las funciones especiales funcionen ($ loop-> have_posts (), $ loop-> the_post (), etc.)

Supongo que esta plantilla incluye el uso de la variable $ post global.

adjuntar (loc_template (‘blocks / content-newsrow.php’)); adjuntar (ubicaci贸n_template (‘bloques / contenido-displayitor.php’)); conectar (loc_template (‘bloques / contenido-altavoz.php’));

Entonces deber铆an funcionar como est谩n.

Me divert铆 mucho resolviendo el rompecabezas. 馃檪

De acuerdo, el c贸digo.


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

Hace 1 a帽o, 8 meses

Hola @vrandom

Vaya, muchas gracias por todo esto, ciertamente te metiste en muchos problemas viendo esto por m铆. Definitivamente no tendr铆a el conocimiento para pensar en algo como esto.

Pegu茅 su clase de extensi贸n en las funciones my.php y puse el c贸digo sql en mi p谩gina -news.php. Despu茅s de cambiar los prefijos de la tabla dentro de la consulta SQL, me enfrento a este error:

Aviso: 铆ndice no especificado: post_type en /wordpress/localhost/website/wp-content/themes/website_theme/functions.php en l铆nea 1131

No estoy seguro de a d贸nde ir para esto, gracias de nuevo.

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

$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();

?>

Esta respuesta fue modificada hace 1 a帽o, 8 meses por.

(@ainsleyclark)

Hace 1 a帽o, 8 meses

Al excavar, mientras imprimo esta variable $ q, encuentro Array ( [posts_per_page] => 6 [found_posts] => 0). Suponiendo que est茅 relacionado con los trabajos encontrados.

(@vrandom)

Hace 1 a帽o, 8 meses

De acuerdo, hice algunas modificaciones.

El problema se redise帽贸 por completo, as铆 como tambi茅n c贸mo estaba calculando el funcionamiento del buscapersonas.

Pru茅balo y cu茅ntame c贸mo te va.


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

Hace 1 a帽o, 8 meses

Hola @vrandom

Gracias nuevamente por su respuesta.

Sigo recibiendo el mismo error. Aviso: 铆ndice no definido: post_type鈥

Copi茅 la clase en functions.php y el resto en mi p谩gina donde quiero mostrar las publicaciones. Cambi茅 todo el wp_ al prefijo de mi tabla, incluido primary_wp, 驴crees que esto es correcto? Tambi茅n cambi茅 mis tipos de trabajos de edici贸n. No s茅 si me falta algo. 隆Definitivamente deber铆as hacer esto en un plugin cuando llegue!

Codigo adjunto:

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

 $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)

Hace 1 a帽o, 8 meses

Humm, solo encontr茅 un lugar donde la frase 芦post_type禄 se usa como clave de 铆ndice. Sin embargo, no estoy seguro de por qu茅 no comete un error en mi sitio de desarrollo.

En la clase WP_Query_CustomSQL, funci贸n get_post,


$q = &$this->query_vars;

$post_type = $q['post_type'];

cambia eso a


$q = &$this->query_vars;

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

(@ainsleyclark)

Hace 1 a帽o, 8 meses

Hola @vrandom

Sin suerte todav铆a, el c贸digo anterior logr贸 deshacerse del error, pero no se est谩n enviando publicaciones, por lo que no genera nada.

Actualmente, la pregunta es sobre taxonom铆a personalizada, estoy agregando este c贸digo con una plantilla de p谩gina para todas las p谩ginas de taxonom铆a. No estoy seguro de si esto ya est谩 en su lugar. Tampoco estoy seguro de qu茅 deber铆a estar en la variable post_slug en la parte superior de la pregunta. 驴Quiz谩s no funciona por eso? No puedo estar seguro

Ser铆a genial si esto pudiera funcionar.

Gracias de nuevo.


$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)

Hace 1 a帽o, 8 meses

Este es el c贸digo original en el que se us贸 $ post_slug.


$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 ) 
	    )
	));

Me parece extra帽o que $ post-> post_name se use para un caracol de taxonom铆a.

Esto es de lo que establec铆 el 煤ltimo sql, pero no ten铆a una taxonom铆a llamada foebar, as铆 que us茅 la categor铆a. Supongo que no tienes una taxonom铆a llamada foebar.

驴Necesita la parte tax_query?

(@ainsleyclark)

Hace 1 a帽o, 8 meses

Hola @vrandom,

Debo haber estado usando $ post_slug para devolver la taxonom铆a, el caracol de correo y el caracol de taxonom铆a tienen la misma URL. La taxonom铆a se llama foebar, y cada una tiene una p谩gina y una Im y usando esta plantilla de una p谩gina para cada una de ellas 5, la idea es que cada p谩gina atraiga oradores, expositores y noticias etiquetadas con la taxonom铆a particular.

En la consulta SQL cambi茅 芦categor铆a禄 al caracol de correo, pero todav铆a no devolv铆 ning煤n resultado. 驴Hay alguna manera de probar lo que est谩 provocando la pregunta SQL?

驴No est谩s 100% seguro de su tax_query?

Muchas gracias.

Esta respuesta fue modificada hace 1 a帽o, 8 meses por.

(@vrandom)

Hace 1 a帽o, 8 meses

As铆 que cre贸 un tipo de taxonom铆a personalizado llamado foobar y lo adjunt贸 a todos los tipos de publicaci贸n personalizados (‘noticias’, ‘expositores’, ‘oradores’).

Ok, pon esto debajo de la l铆nea $ post_slug = $ post-> post_name. Deber铆a volcar un registro de la base de datos usando el tipo de publicaci贸n ‘news’, una taxonom铆a personalizada llamada ‘foobar’ con un caracol de valor $ 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)

Hace 1 a帽o, 8 meses

Hola @vrandom

Se hizo eco de esto:

editar (1) {
[0]=> objeto (stdClass) # 6075 (3) {
[鈥渋d鈥漖=> cadena (3) 芦395禄
[鈥減ost_type鈥漖=> cable (4) 芦noticias禄
[鈥減ost_date鈥漖=> cadena (19) 鈥2019-02-24 09:36:45鈥潁}

驴Solucion贸 tu problema??

0 / 0

Deja una respuesta 0

Tu direcci贸n de correo electr贸nico no ser谩 publicada. Los campos obligatorios est谩n marcados con *