WordPress : Código PHP para Mostrar productos en la portada

Fecha Publicación:       05 de Septiembre de 2022
Fecha Modificación:       03 de Octubre de 2022

Crear el siguiente archivo mostrar_categoria_de_productos_en_portada.php  con el siguiente codigo:

<!-- https://getbootstrap.com/docs/4.0/components/navs/ 
https://ajgallego.gitbook.io/bootstrap-4/componentes-responsive/navegacion
 -->
<?php
 //$path = get_home_path();
?>
<div class="container-fluid pt-2 pb-2">
    <div class="row">
        <div class="col-12">
            <?php
            $products_cats = array();
            $args = array(
                'post_type'      => 'product',
                //Parámetros de orderby y order (ASC/ DESC)
                //https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters
                'orderby'   => 'id',
                'order'     => 'ASC',
                //Parámetros de paginación
                //https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters
                //'posts_per_page'=>-1 se usa (mostrar todas las publicaciones).
                'posts_per_page' => -1,
            );
            $products = new WP_Query($args);
            /* https://developer.wordpress.org/reference/classes/wp_query/#
            have_posts() = Determina si la consulta actual de WordPress tiene publicaciones para recorrer.
            que llama a $wp_query->have_posts(), para ver si hay publicaciones para mostrar.
            */
            if ($products->have_posts()) {
                while ($products->have_posts()) {
                    $products->the_post();
                    $products_categories = get_the_terms(get_the_id(), 'product_cat');
                    foreach ($products_categories as $product_category) {
                        if (!in_array($product_category->name, $products_cats, true)) {
                            array_push($products_cats, $product_category->name);
                        }
                    }
                }
            ?>
                <!-------- INICIO  TAB CABECERA ------------>
                <ul class="nav nav-pills nav-fill mb-3" id="pills-tab" role="tablist">
                    <?php
                    $counter = 0;
                    $class   = '';
                    //  YA NO LO USO PARA ORDENAR ahora el orden lo defino en el mismo array
                    // https://desarrolloweb.com/articulos/ordenar-arrays-php.html
                    //Alex me salia  las categorias el ultima que agregue al principio con la funcion krsort lo ordene
                    /* krsort($products_cats); */
                    $products_cats;
                    foreach ($products_cats as $key => $products_cat) {
                        $counter++;
                        if ($counter == 1) {
                            $class = 'active';
                        } else {
                            $class = '';
                        }
                        // quita los espacios a la categorias y los reemplaza por un -
                        //  Cursos Gis Escritorio = Cursos-Gis-Escritorio
                        $products_cat_sin_espacio = str_replace(' ', '-', $products_cat);
                    ?>
                        <li class="nav-item mi_estilo_nav_item">
                            <a class="nav-link <?php echo $class ?> mi_estilo_nav_link" id="pills-<?php echo $products_cat_sin_espacio ?>-tab" data-toggle="pill" href="#pills-<?php echo $products_cat_sin_espacio ?>" role="tab" aria-controls="pills-<?php echo $products_cat_sin_espacio ?>" aria-selected="false">
                                <?= strtoupper($products_cat) ?>
                            </a>
                        </li>
                    <?php
                    }
                    ?>
                </ul>
                <!-------- FIN  TAB CABECERA ------------>
                <!-------- INICIO  CONTENIDO ------------>
                <div class="tab-content" id="pills-tabContent">
                    <?php
                    $counter = 0;
                    $class   = '';
                    foreach ($products_cats as $key => $products_cat) {
                        $counter++;
                        if ($counter == 1) {
                            $class = 'show active';
                        } else {
                            $class = '';
                        }
                        // quita los espacios a la categorias y los reemplaza por un -
                        //  Cursos Gis Escritorio = Cursos-Gis-Escritorio
                        $products_cat_sin_espacio = str_replace(' ', '-', $products_cat);
                    ?>
                        <div class="tab-pane fade show <?php echo $class ?>" id="pills-<?php echo $products_cat_sin_espacio ?>" role="tabpanel" aria-labelledby="pills-<?php echo $products_cat_sin_espacio ?>-tab">
                            <?php
                            $args = array(
                                'post_type' => 'product',
                                //Parámetros de paginación
                                //https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters
                                //'posts_per_page'=>-1 se usa (mostrar todas las publicaciones).
                                'posts_per_page' => -1,
                                //https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters
                                'tax_query'      => array(
                                    array(
                                        //Producto categoria
                                        'taxonomy' => 'product_cat',
                                        'field'    => 'slug',
                                        'terms'    => array($products_cat),
                                        'operator' => 'IN'
                                    )
                                ),
                            );
                            $div_products = new WP_Query($args);
                            if ($div_products->have_posts()) {
                            ?>
                                <!-- https://www.campusmvp.es/recursos/post/bootstrap-4-4-nuevos-contenedores-fluidos-y-filas-automaticas-de-columnas-fijas.aspx -->
                                <!-- row-cols-1  = por cada fila tendremos una columna
                                 row-cols-4  = por cada fila tendremos 4 columna
                                -->
                                <div class="row">
                                    <?php
                                    while ($div_products->have_posts()) {
                                        $div_products->the_post();
                                        //https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/
                                        //$image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()),'full');
                                          $image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), array('300','300'), true );

                                    ?>
                                        <?php                                       
                                        //recuerda de no porner include_once porque cargaria una sola vez y no mostraria todos los cursos
                                        include($path_mis_funciones . "WooCommerce-mostrar-productos-stilo-card-1.php");
                                        ?>
                                <?php
                                    }
                                }
                                ?>
                                </div> <!-- fin  class="row row-cols-1 row-cols-md-2 g-4" -->
                                <?php
                                wp_reset_postdata();
                                ?>
                        </div>
                    <?php
                    }
                    ?>
                </div>
            <?php
            } else {
                // esc_attr_e('No products listed in the Admin', 'techiefood');
            }
            wp_reset_postdata();
            ?>
        </div>     
    </div>
</div>

 

crear el Archivo WooCommerce-mostrar-productos-stilo-card-1.php   con el siguiente codigo:

<?php // exit; 
/* viene de front-page-mostrar-cursos.php */
?>
<!-- https://getbootstrap.com/docs/5.2/components/card/ -->
<!-- Las Cards  no asumen un widthinicio específico, por lo que tendrán un 100 % de ancho 
a menos que se indique lo contrario.
 Puede cambiar esto según sea necesario con CSS personalizado, grid classes, grid Sass mixins, or utilities. -->
<!-- <div class="col mi_estilo_por_columna slideDown"> -->
<div class="col-sm-12 col-md-3 col-lg-3 mb-5 slideDown">
    <a href="<?= get_permalink($product_id); ?>">
        <div class="card h-100 mi_estilo_card_por_columna">
            <!-- <img style="height:170px" src="<?php echo $image[0]; ?>" alt="<?php echo wp_get_attachment_caption(get_the_ID()) ?>" class="card-img-top"> -->
            <img  src="<?php echo $image[0]; ?>" alt="<?php echo wp_get_attachment_caption(get_the_ID()) ?>" class="card-img-top">
            <div class="card-body">
                <h3 class="card-title mi_estilo_card_title"><?= mb_strtoupper(get_the_title(), 'UTF-8'); ?></h3>
                <p class="card-text mi_estilo_card_text">
                    <?php
                    // the_excerpt() = Muestra la descripcion corta del producto 
                    // sino hay descripcion corta tomara la descripcion larga
                    /* echo the_excerpt();  */
                    /* la funcion    excerpt la encontramos en el archivo functions.php y extrae palabras completas */
                    // de la funcion the_excerpt()
                    echo mifuncion_the_excerpt('15');
                    /* echo "<div style='text-align:justify'>".mifuncion_the_excerpt('15')."</div>";  */
                    ?>
                </p>
            </div>
            <!-- text-muted es la clase bootstrad para dedinir color del texto -->
            <div class="card-footer mi_estilo_card_footer">
                <?php
                $fechainicio = get_field('fecha_inicio');
                // echo gettype($fechainicio) ."-----ica----";exit;
                if (!is_null($fechainicio) and strlen($fechainicio) <> 0) {
                    //  $fechainicio =  the_field('fecha_inicio');
                ?>
                    <small class="font-weight-bold">Fecha Inicio:&nbsp;&nbsp;&nbsp;</small>
                    <small class="mi_estilo_fechainicio">
                        <?php //the_field('fecha_inicio'); 
                        echo $fechainicio;
                        ?>
                    </small>
                <?php
                } else {
                ?>
                    <small class="font-weight-bold">Fecha Inicio:&nbsp;&nbsp;&nbsp;</small>
                    <small class="">
                        <?php //the_field('fecha_inicio'); 
                        echo "Proximamente";
                        ?>
                    </small>
                <?php } ?>
            </div>
        </div> <!-- fin div class="card h-100"> -->
    </a>
</div>

Funciones utilizadas escribir el siguiente codigo en el archivo functions.php: 

<?php 
if (!function_exists('mifuncion_the_excerpt')) {
  //Limitar con la funcion get_the_excerpt en palabras
  /* https://andres-dev.com/limitar-post-excerpt-length-wordpress/ */ 
  function mifuncion_the_excerpt($limit) {
    $excerpt = explode(' ', get_the_excerpt(), $limit);
    if (count($excerpt)>=$limit) {
    array_pop($excerpt);
    $excerpt = implode(" ",$excerpt).'...';
    } else {
    $excerpt = implode(" ",$excerpt);
    }
    $excerpt = preg_replace('`[[^]]*]`','',$excerpt);
    return $excerpt;
  }
}
?>

 

Articulo : 954 - Veces Leidas
Compartir Articulo:
×

¡Apóyame suscribiéndote a mi canal!

Tutoriales sobre Diseño Web