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 ​​en 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) {
[“id”]=> cadena (3) «395»
[“post_type”]=> cable (4) «noticias»
[“post_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.