CSS сетка не работает должным образом при создании PHP - PullRequest
0 голосов
/ 09 октября 2018

Я использую PHP для создания вкладок связанных категорий (выбранных с использованием отношения PODs - созданных в бесплатном плагине Pods), и на каждой вкладке отображаются 3 продукта этих категорий в сеточном формате.Однако моя сетка не отображается должным образом, и я не могу понять, что является причиной проблемы.Я использовал тот же CSS для сетки, что и в другом проекте, поэтому я не уверен, что заставляет макет вести себя так, как он есть.Я сравнил его с другими CSS и html из предыдущего проекта, и единственное, что я вижу, отличается тем, что сетка находится внутри содержимого вкладки.

Я хочу, чтобы продукты были выровнены по центруи находиться на одинаковом расстоянии.

2 Products

3 Products

Мой код указан ниже:

<?php 
/**
*Plugin Name: Related Categories Plugin
*Description: This plugin adds related categories 
*/

// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;

// BEGIN ENQUEUE PARENT ACTION
// AUTO GENERATED - Do not modify or remove comment markers above or below:

// END ENQUEUE PARENT ACTION

function gr_related_categories(){
    //get Pods object for current post
    $pod = pods( 'product', get_the_id() );
    $tabs='';
    $content='';
//get the value for the relationship field
$related = $pod->field( 'related_categories' );
$tabs.= '<style>
            /* Style the tab */
.tab {
    overflow: hidden;
    border: solid 1px #5500B5;
    background-color: #f1f1f1;
    text-align:center;
}

/* Style the buttons inside the tab */
.tab button {
    background-color: inherit;
    border: none;
    outline: none;
    float:none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
    color:black;
    display:inline-block;
}

/* Change background color of buttons on hover */
.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
    background-color: #ccc;
    border:solid 1px #5500B5;
    border-bottom:0px;
    border-top:0px;
}

/* Style the tab content */
.tabcontent {
    display: none;
    border: 1px solid #ccc;
    border-top: none;
    text-align:center;
}



.gr_related_category img{
    object-fit: cover;
    max-height:250px;
    height:250px;
    transition: transform .2s; /* Animation */
    border-radius:0px;
}
.gr_related_category img:hover {
    transform: scale(1.5); /* (150% zoom - Note: if the zoom is too large, it will go outside of the viewport) */
}

.gr_related_category{
    width:250px; 
    height:300px; 
    margin: 20px auto;  
    bakground-color:white; 
    border:solid 2px #5500B5; 
    text-align:center; 
    overflow: hidden;
    vertical-align: bottom;
    }

.gr_related_category_name{
    width:100%;
}
</style>';
if ( ! empty( $related ) ) {
    $tabs.='<div class="tab">';
    foreach ( $related as $rel ) { 
        $id = $rel[ 'term_id' ];
        $term=get_term($id, 'product_cat');

        $name = $rel['name'];
        $slug = $rel['slug'];
        $thumbnail_id = get_term_meta( $id, 'thumbnail_id', true );
        $image=wp_get_attachment_image($thumbnail_id, 'full');
        $cat_url=get_term_link($term);


        $tabs.='<button class="tablinks" onclick="openTab(event, \''.$name.'\' )">'.$name.'</button>';

        $args = array(
        'category' => array( $slug ),
        );

        $products = wc_get_products( $args );

        $content.='<div id="'.$name.'" class="tabcontent">';
        $content.='<div style=" width:100%; display: grid; grid-gap: 0px; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));">';
        $counter=0;

        foreach ( $products as $item_id => $item_obj ) {
                if ($counter < 3){
                $counter=$counter+1;
                $item_data = $item_obj->get_data();
                $product_id=$item_data['id'];
                $title = get_the_title($product_id);
                $link = get_the_permalink($product_id);
                $image = get_the_post_thumbnail($product_id, 'full');
                $data ='<div class="gr_related_category"><a href="'.$link.'" target="blank">'.$image.'<h3 style="color:#5500B5;">'.$title.'</h3></a></div>';
                $content.=$data.'<br>';
                }
        }
        $content.='</div>';
        $content.='<a href='.$cat_url.' target="_blank"><h3 style="color:#5500B5;"\>See All '.$name.'</h3></a>';

        $content.='</div>';
    } //end of foreach
    $tabs.='</div>';
    $tabs.=$content;
    $tabs.='<script>

                function openTab(evt, tabName) {
                    var i, tabcontent, tablinks;
                    tabcontent = document.getElementsByClassName("tabcontent");
                    for (i = 0; i < tabcontent.length; i++) {
                        tabcontent[i].style.display = "none";
                    }
                    tablinks = document.getElementsByClassName("tablinks");
                    for (i = 0; i < tablinks.length; i++) {
                        tablinks[i].className = tablinks[i].className.replace(" active", "");
                    }
                    document.getElementById(tabName).style.display = "block";
                    evt.currentTarget.className += " active";
                }
            </script>';
} //endif ! empty ( $related );
return $tabs;
}

add_shortcode('gr_related_categories', 'gr_related_categories');
?>

1 Ответ

0 голосов
/ 10 октября 2018

Проблема была вызвана тем, что тег не в том месте.Это должно было быть за пределами цикла foreach.

                    foreach ( $products as $item_id => $item_obj ) {
                        if ($counter < 3){
                        $counter=$counter+1;
                        $item_data = $item_obj->get_data();
                        $product_id=$item_data['id'];
                        $title = get_the_title($product_id);
                        $link = get_the_permalink($product_id);
                        $image = get_the_post_thumbnail($product_id, 'full');
                        $data ='<div class="gr_related_category"><a href="'.$link.'" target="blank">'.$image.'<h3 style="color:#5500B5;">'.$title.'</h3></a></div>';
                        $content.=$data;
                }
        }
        $content.='</div></br>';
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...