2017-01-24 10 views
1

EDIT: Я значительно упростил свой код, чтобы узнать, могу ли я на самом деле заставить HTML выходить, но не повезло.Выходной код HTML в пользовательском shortcode для WooCommerce

Вот упрощенная версия, удалив все мои собственные HTML и добавив только <div class="test"></div>, чтобы узнать, могу ли я получить свой shortcode для вывода HTML, чего нет.

//custom shortcodes 
function product_snippet($atts) { 

// Attributes 
$atts = shortcode_atts(
    array(
     'id' => '', 
     'snippet' => '', 
    ), 
    $atts, 
    'product_snippet' 
); 

return $product = wc_get_product($atts['id']); 
return $product_img = $product->get_image(); 
return $product_title = $product->get_title(); 
return $product_link = get_permalink($atts['id']); 
return $children = $product->get_children(); 
return $children_array = array(); 
echo "<div class='test'></div>"; 


} 
add_shortcode('product_snippet', 'product_snippet'); 

Это останавливает сайт от сбоев, но не выводится HTML.

ОРИГИНАЛЬНАЯ ПОЧТА: Я пытаюсь написать специальный шорт-код, чтобы мой клиент мог более легко редактировать свой веб-сайт. Я добавил следующий код в файл functions.php WordPress, и я не могу определить, почему он не работает.

Идея состоит в том, чтобы вводить идентификатор сгруппированного продукта в короткий код, и он подтягивает продукты Title, Image и все дочерние продукты.

function product_snippet($atts) { 
$a = shortcode_atts(array (
     'id', 
     'snippet', 
    ), $atts); 

$product = wc_get_product($a['id']); 
$product_img = $product->get_image(); 
$product_title = $product->get_title(); 
$product_link = get_permalink($a['id']); 
$children = $product->get_children(); 

//initialize array so that child products can be sorted by price. 
$children_array = array(); 

//Assign each child product to its price in array so that child products can be sorted by price in HTML. 
foreach ($children as $key => $value) { 
     $children_array[$value] = wc_get_product($value)->get_price(); 

    }; 
    asort($children_array); 

return '<div class="main_pro"> 

      <div class="left-sd">' . do_shortcode('[product id="' . $a['id'] . '"]') . '</div> 
      <div class="right-sd"> 
      <div class="info"> 
       <h2>'. $product_title . '</h2> 
       <p>' . $a['snippet'] . '&nbsp;<a href="' . $product_link . '">More Info &gt;&gt;</a></p> 
      </div> 
       <ul> 
         ' . foreach ($children_array as $key => $value) { 
          $option = wc_get_product($key); 
           $option_title = $option->post->post_title; 
         . ' 
         <li> 
           <div id="outer-bar"> 
            <div class="bar-l"> 
              ' . $option_title; 
              if ($option->get_attribute('pa_pack-size')) { 
               strval(wc_get_product($key)->get_attribute('pa_pack-size')); 
               .'<br/> 
               <span class="small_pz"> 

                 ' . "$" . strval(round(($option->get_price()/intval($option->get_attribute('pa_pack-size'))), 2)) . " per tray - SAVE $" . strval(round(($product->get_price() * $option->get_price() - $option->get_price()), 2)); . ' 
               </span> 
              ' . } 
            . '</div> 

            <div class="bar-r">' . do_shortcode('[add_to_cart id="' . $key . '"]'); . '</div> 
          </div> 
         </li> 
         ' . } 
       . ' </ul> 
      </div> 
    </div>'; 
}; 
add_shortcode('product_snippet', 'product_snippet'); 

Предположим, у меня есть открытие и закрытие <?php ?> тегов. Я много не пишу в PHP, поэтому извиняюсь, если мой код janky. Если я смогу приблизиться к лучшим практикам (я не думаю, что моя конкатенация выглядит правильно), я открыт для обратной связи.

+0

Что он выводит в тот момент, когда вы помещаете шорт-код в сообщение? – AceWebDesign

+0

Введенный код возвращает ошибку 500. Когда я удаляю 'return 'div class =" main_pro "...' и весь следующий HTML-код, ввод короткого кода в страницу приводит только к навигации по загрузке страницы. – user3183717

ответ

1

В коде было множество ошибок. Попробуй это.

function product_snippet($atts) 
{ 
    $a = shortcode_atts(array(
     'id', 
     'snippet', 
    ), $atts); 

    $product = wc_get_product($a['id']); 
    $product_img = $product->get_image(); 
    $product_title = $product->get_title(); 
    $product_link = get_permalink($a['id']); 
    $children = $product->get_children(); 

//initialize array so that child products can be sorted by price. 
    $children_array = array(); 

//Assign each child product to its price in array so that child products can be sorted by price in HTML. 
    foreach ($children as $key => $value) { 
     $children_array[$value] = wc_get_product($value)->get_price(); 

    }; 
    asort($children_array); 


    $string = '<div class="main_pro"> 

      <div class="left-sd">' . do_shortcode('[product id="' . $a['id'] . '"]') . '</div> 
      <div class="right-sd"> 
      <div class="info"> 
       <h2>' . $product_title . '</h2> 
       <p>' . $a['snippet'] . '&nbsp;<a href="' . $product_link . '">More Info &gt;&gt;</a></p> 
      </div> 
       <ul>'; 
    foreach ($children_array as $key => $value) { 
     $option = wc_get_product($key); 
     $option_title = $option->post->post_title; 
     $string .= ' 
         <li> 
           <div id="outer-bar"> 
            <div class="bar-l"> 
              ' . $option_title; 
     if ($option->get_attribute('pa_pack-size')) { 
      strval(wc_get_product($key)->get_attribute('pa_pack-size')); 
      $string .= '<br/> 
               <span class="small_pz"> 

                 ' . "$" . strval(round(($option->get_price()/intval($option->get_attribute('pa_pack-size'))), 2)) . " per tray - SAVE $" . strval(round(($product->get_price() * $option->get_price() - $option->get_price()), 2)) . 
       '</span>'; 
     } 

     $string .= '</div> 

            <div class="bar-r">' . do_shortcode('[add_to_cart id="' . $key . '"]') . '</div> 
          </div> 
         </li> 
         '; 
    } 
    $string .= ' </ul> 
      </div> 
    </div>'; 
    return $string; 
} 


add_shortcode('product_snippet', 'product_snippet'); 
+0

Я не проверял, что функции, которые вы используете, работают, но php теперь должен нормально укладываться. – AceWebDesign

+0

Быстрая копия/вставка дает мне проблему, когда появляется только заголовок/nav моего сайта WP. Я думаю, что я выделил проблему: по какой-то причине '$ product_img = $ product-> get_image(); $ product_title = $ product-> get_title(); $ product_link = get_permalink ($ a ['id']); $ children = $ product-> get_children(); ' Либо некоторые, либо все эти переменные вызывают сбои. Но с вашими изменениями кода я должен быть в состоянии идти по правильному пути. Я уточню это, когда узнаю ответ. – user3183717

+0

также может использовать $ product_title = $ product-> post-> post_title; чтобы установить имя – AceWebDesign

1

Я немного изменил ваш код, чтобы он работал. Это просто пример, который вы можете выполнить. Попробуйте и дайте мне знать:

//custom shortcodes 
if(!function_exists('product_snippet')) {  

    function product_snippet($atts) { 

     // Attributes 
     extract(shortcode_atts( 
      array(
       'id' => '', // You will use $id to get the value of this attribute 
       'snippet' => '' // You will use $snippet to get the value of this attribute 
      ), 
      $atts 
     )); 

     // Get an instance of the product object 
     $product = wc_get_product($id); 

     // Displays go here 
     return '<div class="test">'.$product->get_image().'<a href="'.get_permalink($id).'">'.$product->get_title().'</a></div>'; 

    } 

    add_shortcode('product_snippet', 'product_snippet'); 
} 

Вы должны получить результат, HTML на этот раз ...

код идет в function.php файл вашей активной темы ребенка (или темы), или же в любом файле плагина ,

 Смежные вопросы

  • Нет связанных вопросов^_^