text Magento WordPress集成
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text Magento WordPress集成相关的知识,希望对你有一定的参考价值。
1) Проинсталь Magento в ту же базу, папку с WP!
2) Если автоматом не подключилось к базе, пропиши в админке вручную как называется папка с блогом.
3) Скопируй темплейты и xml из базовой темы.
----------------- Recent Posts Block
http://fishpig.co.uk/wordpress-integration/docs/recent-posts-block.html
http://www.demacmedia.com/magento-commerce/mini-tutorial-full-integration-fishpig-wordpress-with-custom-post-types-and-fields/
<!--/** * Display a list of your 5 most recent WordPress Posts * * {\{block type="wordpress/sidebar_widget_posts" name="wordpress.widget.recent_posts" post_count="5" title="Latest Posts" template="wordpress/sidebar/widget/posts.phtml"}} */-->
<reference name="content">
<block type="wordpress/sidebar_widget_posts" name="wordpress.widget.recent_posts" as="recent_posts" template="wordpress/sidebar/widget/posts.phtml">
<action method="setTitle"><title>Latest Posts</title></action>
<action method="setPostCount"><post_count>5</post_count></action>
</block>
</reference>
------- by a Category ID
<!-- category_id="1" --> <action method="setCategoryId"><id>1</id></action>
------- by an Author ID
<!-- author_id="1" --> <action method="setAuthorId"><id>1</id></action>
------- by a Category ID and a Author ID
<!-- author_id="1" category_id="1" -->
<action method="setCategoryId"><id>1</id></action>
<action method="setAuthorId"><id>1</id></action>
------- by a Custom Post Type
<!-- author_id="1" --> <action method="setPostType"><type>article</type></action>
---------------- Recent Posts с фичеред картинкой (ресайз timthumb.php), вывод иконо категори (через константы мадженты)
Для правильной работы скрипта timthumb.php необходимо
1] Обновить скрипт до новой версии.
Пройдите по ссылке timthumb.googlecode.com/svn/trunk/timthumb.php
Выделите весь текст (Ctrl+A), скопируйте и замените скопированной частью содержимое файла timthumb.php, который находится в корне папки с файлами темы.
Затем, в конце файла добавьте следующие два символа "?>"
Сохраните файл timthumb.php и закачайте на сервер.
2] Обязательно наличие в папке темы директории "cache".
3] Права (CHMOD) на директорию "cache" должны быть 777.
<section class="products-new-container">
<div class="holder">
<?php if ($title = $this->getTitle()): ?>
<h1><?php echo $this->__($title) ?></h1>
<?php endif; ?>
<ul class="products-new-list">
<?php foreach($posts as $post): ?>
<li>
<?php if($featuredImage = $post->getFeaturedImage()): ?>
<a href="<?php echo $post->getPermalink() ?>" class="product-image">
<span class="product-image-holder">
<em class="mask"><?php echo $this->__('mask'); ?></em>
<img src="<?php echo str_replace('/index.php', '', $this->getUrl('')); ?>timthumb.php?src=<?php echo $featuredImage->_data['guid']; ?>&w=170&h=170&zc=1" alt="<?php echo $this->escapeHtml($post->getPostTitle()) ?>" />
<?php
$garden_guide_category_id = Mage::getModel('core/variable')->loadByCode('garden_guide_category_id')->getValue('plain');
$gallery_category_id = Mage::getModel('core/variable')->loadByCode('gallery_category_id')->getValue('plain');
$watchin_grow_id = Mage::getModel('core/variable')->loadByCode('watchin_grow_id')->getValue('plain');
$post_categies = $post->getData('category_ids');
$catpreview = '';
if(!empty($post_categies))
{
switch($post_categies[0])
{
case '1': $catpreview = '<span class="icon icon-article">icon</span>';
break;
case $garden_guide_category_id: $catpreview = '<span class="icon icon-article">icon</span>';
break;
case $gallery_category_id: $catpreview = '<span class="icon icon-photo">icon</span>';
break;
case $watchin_grow_id: $catpreview = '<span class="icon icon-video">icon</span>';
break;
default: $catpreview = '';
break;
}
}
if(!empty($catpreview)){ echo $catpreview; }
?>
</span>
</a>
<?php endif; ?>
<h2><a href="<?php echo $post->getPermalink() ?>"><?php echo $this->htmlEscape($post->getPostTitle()) ?></a></h2>
<?php if($post->getPostExcerpt()): ?>
<p><?php echo $post->getPostExcerpt() ?></p>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
</section>
---------------- Associated Blog Posts рилейтид посты (сортировка не работает)
<reference name="product.info">
<block type="wordpress/post_associated" name="related-posts" as="related-posts" template="wordpress/post/associated.phtml">
<action method="setTitle" translate="title" module="wordpress"><title><![CDATA[Related Blog Posts]]></title></action>
<action method="setEntity"><type><![CDATA[product]]></type></action>
<action method="setCount"><count>3</count></action>
</block>
</reference>
<reference name="product.info.additional">
<remove name="wordpress_posts_associated"/>
</reference>
*************************** Пост ********************
----------------- загрузить пост по айдишнику обычно и из посттайпа
$post = Mage::getModel('wordpress/post')->load($post_id);
$post = Mage::getModel('wordpress/post')->setPostType('author-profile')-load($postId);
----------------- кастомфилд поста
echo $post->getMetaValue('your_meta_key');
*************************** Категории ********************
------------- загрузить категорию по ID
<?php
$category = Mage::getModel('wordpress/post_category')->load(2);
echo $category->getName();
?>
------------- посты по ID/Slug категории
<?php
$collection = Mage::getResourceModel('wordpress/post_collection')->addCategoryIdFilter(2);
foreach($collection as $post)
{
echo $post->getData('post_title');
}
?>
addCategorySlugFilter($categorySlug : string)
------------- категории поста
<?php print_r($post->getData('category_ids')); ?>
<?php
if (count($categories = $post->getParentCategories()) > 0) {
foreach($categories as $category) {
echo 'url : '.$category->getUrl().'<br/>';
echo 'name : '.$category->getName().'<br/>';
echo 'id : '.$category->getId().'<br/>';
}
}
?>
---- Виджет категорий через php
<?php echo Mage::getSingleton('core/layout')->createBlock('wordpress/sidebar_widget_categories')->setTemplate('wordpress/sidebar/widget/categories.phtml')->toHtml() ?>
----------------- Посты по айдишнику тега
XML
<block type="wordpress/tag_view" name="wp.post.tag" template="wordpress/tag/view.phtml">
<block type="wordpress/post_list" name="wordpress_post_list" as="post_list" template="wordpress/post/list.phtml" />
<action method="setTagId"><id>7</id></action>
</block>
*************************** Посттайп ********************
------------- посты посттайпа
<?php
$collection = Mage::getResourceModel('wordpress/post_collection')->addPostTypeFilter('news');
foreach($collection as $post)
{
echo $post->getData('post_title');
}
?>
***************************** Тэги ************************
----------------- загрузить тэг по ID
<?php
$tag = Mage::getModel('wordpress/post_tag')->load(9);
echo $tag->getName();
?>
----------------- посты по ID тега
<?php
$collection = Mage::getResourceModel('wordpress/post_collection')->addTagIdFilter('8');
foreach($collection as $post)
{
echo $post->getData('post_title');
}
?>
<?php
if (count($tags = $post->getTags()) > 0) {
foreach($tags as $tag) {
echo 'url : '.$tag->getUrl().'<br/>';
echo 'name : '.$tag->getName().'<br/>';
echo 'id : '.$tag->getId().'<br/>';
}
}
?>
----------------- так можно получить список категорий/теги поста, как на meta.phtml
<?php
$a = new Fishpig_Wordpress_Block_Post_Meta();
echo $a->getCategoryString($post);
?>
----------------- Add a WordPress Menu Anywhere in Magento
------- Using XML
<block type="wordpress/menu" name="wp.menu">
<action method="setMenuId"><id>48</id></action>
<action method="setListId"><id>my-menu</id></action>
</block>
------- Using PHP
<?php $menu = Mage::getSingleton('core/layout')
->createBlock('wordpress/menu')
->setMenuId(48)
->setListId('my-menu') ?>
<?php echo $menu->toHtml() ?>
Позволяет выводить блоки Magento на страничках WP
http://wordpress.org/plugins/magento-wordpress-integration/
http://www.mwi-plugin.com/documentation/default-blocks/
http://demo.mwi-plugin.com/
<?php the_block('head'); ?>
<?php the_static_block("left-customer-srvices"); ?>
=========================== Magento плагин для WP wordpress ==============================
Использует SOAP соединение, придется создать юзера и рольк на бэкенде мадженты.
Вебсервере должен понимать WSDL и должно быть установлено расширение php-soap
http://wordpress.org/plugins/magento/
[magento pid='2, 1']
[magento cat='jeans'] = [magento cat='5']
Продукт из категории
[magento cat='jeans, 3']
Or:
[magento cat='5, 3']
Последние продукты
[magento latest='3']
Серч по имени
[magento name_like='ball, 2']
----------------- если на хоум выводятся посты блога с пагинацией, есть проблемы с пагинацией надо поменять урлы на /?page=2
----- Блог на хоум с пейджером
<reference name="content">
<block type="wordpress/homepage" name="wordpress_homepage" as="wp.home" template="wordpress/homepage.phtml">
<block type="wordpress/post_list" name="wordpress_post_list" as="post_list" template="wordpress/post/list.phtml">
<block type="core/text_list" name="post.content.before" as="before_post_content" />
<block type="core/text_list" name="post.content.after" as="after_post_content">
<block type="wordpress/post_meta" name="post.view.meta" as="meta" after="-" template="wordpress/post/meta.phtml" />
</block>
<block type="wordpress/post_list_pager" name="wordpress_post_list.pager" as="pager" template="page/html/pager-blog-home.phtml" />
</block>
</block>
</reference>
----- Темплейт для кастомного пейджера page/html/pager-blog-home.phtml
<?php if($this->getCollection()->getSize()): ?>
<?php if($this->getLastPageNum()>1): ?>
<div class="pagination">
<ul>
<?php if (!$this->isFirstPage()):
$url = ''; $url = explode('/',substr($this->getPreviousPageUrl(), strpos($this->getPreviousPageUrl(),'page/')));
?>
<li>
<a class="prev" href="<?php echo $this->getUrl().'?'.$url['0'].'='.$url['1']; ?>" title="<?php echo $this->__('Previous') ?>"><</a>
</li>
<?php endif;?>
<?php if ($this->canShowFirst()):
$url = ''; $url = explode('/',substr($this->getFirstPageUrl(), strpos($this->getFirstPageUrl(),'page/')));
?>
<li><a class="first" href="<?php echo $this->getUrl().'?'.$url['0'].'='.$url['1']; ?>">1</a></li>
<?php endif;?>
<?php if ($this->canShowPreviousJump()):
$url = ''; $url = explode('/',substr($this->getPreviousJumpUrl(), strpos($this->getPreviousJumpUrl(),'page/')));
?>
<li><a class="previous_jump" title="" href="<?php echo $this->getUrl().'?'.$url['0'].'='.$url['1']; ?>">...</a></li>
<?php endif;?>
<?php foreach ($this->getFramePages() as $_page): ?>
<?php if ($this->isPageCurrent($_page)): ?>
<li class="current"><?php echo $_page ?></li>
<?php else:
$url = ''; $url = explode('/',substr($this->getPageUrl($_page), strpos($this->getPageUrl($_page),'page/')));
?>
<li><a href="<?php echo $this->getUrl().'?'.$url['0'].'='.$url['1']; ?>"><?php echo $_page ?></a></li>
<?php endif;?>
<?php endforeach;?>
<?php if ($this->canShowNextJump()):
$url = ''; $url = explode('/',substr($this->getNextJumpUrl(), strpos($this->getNextJumpUrl(),'page/')));
?>
<li><a class="next_jump" title="" href="<?php echo $this->getUrl().'?'.$url['0'].'='.$url['1']; ?>">...</a></li>
<?php endif;?>
<?php if ($this->canShowLast()):
$url = ''; $url = explode('/',substr($this->getLastPageUrl(), strpos($this->getLastPageUrl(),'page/')));
?>
<li><a class="last" href="<?php echo $this->getUrl().'?'.$url['0'].'='.$url['1']; ?>"><?php echo $this->getLastPageNum() ?></a></li>
<?php endif;?>
<?php
if (!$this->isLastPage()):
$url = ''; $url = explode('/',substr($this->getNextPageUrl(), strpos($this->getNextPageUrl(),'page/')));
?>
<li>
<a class="next" href="<?php echo $this->getUrl().'?'.$url['0'].'='.$url['1']; ?>" title="<?php echo $this->__('Next') ?>">></a>
</li>
<?php endif;?>
</ol>
</div>
<?php endif; ?>
<?php endif ?>
----------------- Recent Posts Block
http://fishpig.co.uk/wordpress-integration/docs/recent-posts-block.html
http://www.demacmedia.com/magento-commerce/mini-tutorial-full-integration-fishpig-wordpress-with-custom-post-types-and-fields/
<!--/** * Display a list of your 5 most recent WordPress Posts * * {\{block type="wordpress/sidebar_widget_posts" name="wordpress.widget.recent_posts" post_count="5" title="Latest Posts" template="wordpress/sidebar/widget/posts.phtml"}} */-->
<reference name="content">
<block type="wordpress/sidebar_widget_posts" name="wordpress.widget.recent_posts" as="recent_posts" template="wordpress/sidebar/widget/posts.phtml">
<action method="setTitle"><title>Latest Posts</title></action>
<action method="setPostCount"><post_count>5</post_count></action>
</block>
</reference>
<?php
$posts = $this->getPosts();
$_helper = $this->helper('catalog/output');
?>
<?php if (count($posts) > 0): ?>
<section class="section section-news">
<?php if ($title = $this->getTitle()): ?>
<h1><?php echo $this->__($title) ?></h1>
<?php endif; ?>
<div class="news">
<?php foreach($posts as $post): ?>
<article>
<?php
$featuredImage = $post->getFeaturedImage();
if($featuredImage):
$thumbName = $featuredImage->_data['sizes']['home-news']['file'];
if(empty($thumbName))
{
$featuredImage = $featuredImage->_data['guid'];
}else{
$featuredImage = explode("/", $featuredImage->_data['guid']);
$featuredImage[8] = $thumbName;
$featuredImage = implode("/", $featuredImage);
}
?>
<a href="<?php echo $post->getPermalink() ?>">
<img src="<?php echo $featuredImage; ?>" width="265" height="200" alt="<?php echo $this->escapeHtml($post->getPostTitle()) ?>" />
</a>
<?php endif; ?>
<h2><a href="<?php echo $post->getPermalink() ?>"><?php echo $this->htmlEscape($post->getPostTitle()) ?></a></h2>
<time datetime="<?php echo date('Y-m-d', strtotime($post->getPostDate())); ?>"><?php echo $post->getPostDate(); ?></time>
</article>
<?php endforeach; ?>
</div>
<a href="<?php echo $this->getUrl('blog'); ?>" class="btn-more"><?php echo $this->__('VIEW ALL MOTO NEWS'); ?></a>
</section>
<?php endif; ?>
------- by a Category ID
<!-- category_id="1" --> <action method="setCategoryId"><id>1</id></action>
------- by an Author ID
<!-- author_id="1" --> <action method="setAuthorId"><id>1</id></action>
------- by a Category ID and a Author ID
<!-- author_id="1" category_id="1" -->
<action method="setCategoryId"><id>1</id></action>
<action method="setAuthorId"><id>1</id></action>
------- by a Custom Post Type
<!-- author_id="1" --> <action method="setPostType"><type>article</type></action>
---------------- Recent Posts с фичеред картинкой (ресайз timthumb.php), вывод иконо категори (через константы мадженты)
Для правильной работы скрипта timthumb.php необходимо
1] Обновить скрипт до новой версии.
Пройдите по ссылке timthumb.googlecode.com/svn/trunk/timthumb.php
Выделите весь текст (Ctrl+A), скопируйте и замените скопированной частью содержимое файла timthumb.php, который находится в корне папки с файлами темы.
Затем, в конце файла добавьте следующие два символа "?>"
Сохраните файл timthumb.php и закачайте на сервер.
2] Обязательно наличие в папке темы директории "cache".
3] Права (CHMOD) на директорию "cache" должны быть 777.
Наши темы используют скрипт timthumb.php для обработки изображений. Если при попытке обращения напрямую к нему вы получаете сообщение “Запрос небезопасен и был отвергнут”, а сами изображения просто не прогружаются (хостинг sweb.ru), поможет следующий способ:
Откройте файл .htaccess (в корне сайта) и добавьте следующие строки:
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
<section class="products-new-container">
<div class="holder">
<?php if ($title = $this->getTitle()): ?>
<h1><?php echo $this->__($title) ?></h1>
<?php endif; ?>
<ul class="products-new-list">
<?php foreach($posts as $post): ?>
<li>
<?php if($featuredImage = $post->getFeaturedImage()): ?>
<a href="<?php echo $post->getPermalink() ?>" class="product-image">
<span class="product-image-holder">
<em class="mask"><?php echo $this->__('mask'); ?></em>
<img src="<?php echo str_replace('/index.php', '', $this->getUrl('')); ?>timthumb.php?src=<?php echo $featuredImage->_data['guid']; ?>&w=170&h=170&zc=1" alt="<?php echo $this->escapeHtml($post->getPostTitle()) ?>" />
<?php
$garden_guide_category_id = Mage::getModel('core/variable')->loadByCode('garden_guide_category_id')->getValue('plain');
$gallery_category_id = Mage::getModel('core/variable')->loadByCode('gallery_category_id')->getValue('plain');
$watchin_grow_id = Mage::getModel('core/variable')->loadByCode('watchin_grow_id')->getValue('plain');
$post_categies = $post->getData('category_ids');
$catpreview = '';
if(!empty($post_categies))
{
switch($post_categies[0])
{
case '1': $catpreview = '<span class="icon icon-article">icon</span>';
break;
case $garden_guide_category_id: $catpreview = '<span class="icon icon-article">icon</span>';
break;
case $gallery_category_id: $catpreview = '<span class="icon icon-photo">icon</span>';
break;
case $watchin_grow_id: $catpreview = '<span class="icon icon-video">icon</span>';
break;
default: $catpreview = '';
break;
}
}
if(!empty($catpreview)){ echo $catpreview; }
?>
</span>
</a>
<?php endif; ?>
<h2><a href="<?php echo $post->getPermalink() ?>"><?php echo $this->htmlEscape($post->getPostTitle()) ?></a></h2>
<?php if($post->getPostExcerpt()): ?>
<p><?php echo $post->getPostExcerpt() ?></p>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
</section>
---------------- Associated Blog Posts рилейтид посты (сортировка не работает)
<reference name="product.info">
<block type="wordpress/post_associated" name="related-posts" as="related-posts" template="wordpress/post/associated.phtml">
<action method="setTitle" translate="title" module="wordpress"><title><![CDATA[Related Blog Posts]]></title></action>
<action method="setEntity"><type><![CDATA[product]]></type></action>
<action method="setCount"><count>3</count></action>
</block>
</reference>
<reference name="product.info.additional">
<remove name="wordpress_posts_associated"/>
</reference>
--------------- Рилейтид посты к категории ----------------
<?php
$_category = Mage::registry('current_category');
if ($_category) {
$_helper = $this->helper('wordpress/associations');
$_postIds = $_helper->getAssociations('category/post', $_category->getId());
$_postIds = array_keys($_postIds);
}
$posts = Mage::getResourceModel('wordpress/post_collection')
->setOrderByPostDate()
->addIsPublishedFilter()
->addFieldToFilter('ID', array('IN' => $_postIds))
->setPageSize(2)
->setCurPage(1);
?>
*************************** Пост ********************
----------------- загрузить пост по айдишнику обычно и из посттайпа
$post = Mage::getModel('wordpress/post')->load($post_id);
$post = Mage::getModel('wordpress/post')->setPostType('author-profile')-load($postId);
----------------- картинка
<?php
$featuredImage = $post->getFeaturedImage();
if($featuredImage):
$thumbName = $featuredImage->_data['sizes']['single-post-thumbnail']['file'];
if($width = $featuredImage->_data['sizes']['single-post-thumbnail']['width'])
{
$width = 'width="'.$width.'"';
}
if($height = $featuredImage->_data['sizes']['single-post-thumbnail']['height'])
{
$height = 'height="'.$height.'"';
}
if(empty($thumbName))
{
$featuredImage = $featuredImage->_data['guid'];
}else{
$featuredImage = explode("/", $featuredImage->_data['guid']);
$featuredImage[8] = $thumbName;
$featuredImage = implode("/", $featuredImage);
}
?>
<div class="photo">
<img src="<?php echo $featuredImage; ?>" <?php echo $width.' '.$height; ?> alt="<?php echo $this->escapeHtml($post->getPostTitle()) ?>" />
</div>
<?php endif; ?>
----------------- кастомфилд поста
echo $post->getMetaValue('your_meta_key');
---------------- post comments
<?php
$post = Mage::getModel('wordpress/post')->load(35);
$post_comments = $post->getComments();
if(!empty($post_comments))
{
foreach($post_comments as $comment)
{
print_r($comment);
}
}
?>
*************************** Категории ********************
------------- загрузить категорию по ID
<?php
$category = Mage::getModel('wordpress/post_category')->load(2);
echo $category->getName();
?>
------------- посты по ID/Slug категории
<?php
$collection = Mage::getResourceModel('wordpress/post_collection')->addCategoryIdFilter(2)->addIsPublishedFilter();
foreach($collection as $post)
{
echo $post->getData('post_title');
}
?>
addCategorySlugFilter($categorySlug : string)
------------- категории поста
<?php print_r($post->getData('category_ids')); ?>
<?php
if (count($categories = $post->getParentCategories()) > 0) {
foreach($categories as $category) {
echo 'url : '.$category->getUrl().'<br/>';
echo 'name : '.$category->getName().'<br/>';
echo 'id : '.$category->getId().'<br/>';
}
}
?>
---- Виджет категорий через php
<?php echo Mage::getSingleton('core/layout')->createBlock('wordpress/sidebar_widget_categories')->setTemplate('wordpress/sidebar/widget/categories.phtml')->toHtml() ?>
*************************** Посттайп ********************
------------- посты посттайпа
<?php
$collection = Mage::getResourceModel('wordpress/post_collection')->addPostTypeFilter('news')->addIsPublishedFilter();
foreach($collection as $post)
{
echo $post->getData('post_title');
}
?>
***************************** Тэги ************************
----------------- загрузить тэг по ID
<?php
$tag = Mage::getModel('wordpress/post_tag')->load(9);
echo $tag->getName();
?>
----------------- посты по ID тега
<?php
$collection = Mage::getResourceModel('wordpress/post_collection')->addTagIdFilter('8');
foreach($collection as $post)
{
echo $post->getData('post_title');
}
?>
<?php
if (count($tags = $post->getTags()) > 0) {
foreach($tags as $tag) {
echo 'url : '.$tag->getUrl().'<br/>';
echo 'name : '.$tag->getName().'<br/>';
echo 'id : '.$tag->getId().'<br/>';
}
}
?>
XML
<block type="wordpress/tag_view" name="wp.post.tag" template="wordpress/tag/view.phtml">
<block type="wordpress/post_list" name="wordpress_post_list" as="post_list" template="wordpress/post/list.phtml" />
<action method="setTagId"><id>7</id></action>
</block>
-------------- пользователи авторы автор author
----- все авторы постов
<?php $authors = Mage::getResourceModel('wordpress/user_collection') ?>
<?php if (count($authors) > 0): ?>
<ul>
<?php foreach($authors as $author): ?>
<li>
<a href="<?php echo $author->getUrl() ?>"><?php echo $author->getDisplayName() ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
----- информация об авторе граватар биография, любой кастомфилд в том числе и acf
<?php
echo $post->getAuthor()->getMetaValue('description'); ?>
<?php echo $post->getAuthor()->getGravatarUrl(70); ?>
<?php echo $author->getMetaValue('social'); ?>
----------- Посты посттайпа по автору (можно и обычные и страницы)
<?php
$collection = Mage::getResourceModel('wordpress/post_collection')->addPostTypeFilter('news')->addAuthorIdFilter(5)->addIsPublishedFilter();
foreach($collection as $post)
{
echo $post->getData('post_title').'<br />';
}
?>
----------------- так можно получить список категорий/теги поста, категории поста как на meta.phtml
<?php
$a = new Fishpig_Wordpress_Block_Post_Meta();
echo $a->getCategoryString($post);
echo $a->getTagString($post);
?>
<?php
$post_meta = new Fishpig_Wordpress_Block_Post_Meta();
if($post_tags = explode(',',$post_meta->getTagString($post))):
?>
<ul class="post-tags">
<?php foreach($post_tags as $tag): ?>
<li><?php echo $tag; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
----------------- Add a WordPress Menu Anywhere in Magento
------- Using XML
<block type="wordpress/menu" name="wp.menu">
<action method="setMenuId"><id>48</id></action>
<action method="setListId"><id>my-menu</id></action>
</block>
------- Using PHP
<?php $menu = Mage::getSingleton('core/layout')
->createBlock('wordpress/menu')
->setMenuId(48)
->setListId('my-menu') ?>
<?php echo $menu->toHtml() ?>
---------------------- Other filters (author, publiched, post data, post parent, post type, search, status, term id, meta customfields, multiple filters category)
->addAuthorIdFilter($authorId : int) *****+*****
->addIsPublishedFilter() *****+*****
->addPostDateFilter(dateStr : string) e.g addPostDateFilter(array('from'=>'2013-11')) *****+*****
->addPostDateFilter(array('from'=>'2012-12','to'=>'2013-12')) *****+*****
->addPostParentIdFilter(postParentId : int) *****+*****
->addPostTypeFilter(postType: array|string) *****+*****
->addSearchStringFilter($word : array, $fields : array, [operator = 'OR']) *****+*****
->addStatusFilter(status: array|string) *****+*****
- filter by post status, e.g publish, schedule, trash and etc.
->addTermFilter(term, type : string, field = ‘slug’) e.g. addTermFilter(array('cat1','cat2'),'category') *****+*****
->addTermIdFilter($termId, $type) *****+*****
->addMetaFieldToFilter(metakey, filter: string | array) e.g. addMetaFieldToFilter(‘custom-val’,array(1,2,3)) *****+*****
->addMetaFieldToFilter('video_url', array('1','2'));
->addCustomFieldFilter('video_url', array('1','3'), 'NOT IN'); (Работает не со всеми операторами сравнения, все не пробовал тестить)
->addMetaFieldToSort($field, $dir = 'asc')
->setOrderByCommentCount($dir = 'desc')
->orderByMenuOrder($dir = 'asc')
Multiple Filters Collection Example:
The follow collection the post based on termId, a MetaField and post type filters.
$collection = Mage::getResourceModel('wordpress/post_collection')
->addTermIdFilter(array(1,2,3),'category') //Matches any term in the array, the term may be category, post_tag and etc.
->addMetaFieldToFilter('wpcf-featured-on-category',1) //Matches custom field value
->addPostTypeFilter(array('type1','type2')) //Matches the post type in the array
$collection->getSelect()->order(new Zend_Db_Expr('RAND()')); //This randomizes the selection
----------------- archive date filter
addArchiveDateFilter($archiveDate, $isDaily = false) e.g addArchiveDateFilter(’2013/09/10?)
- filter by date in ‘yyyy’,'yyyy/mm’,'yyyy/mm/dd’ format. The isDaily flag forces the date to behave in ‘yyyy/mm/dd’ format, if you use ’2013/09? with the flag set to true, it won’t return anything.
addCategoryAndPostIdFilter($postIds, $categoryIds, $operator = ‘OR’) e.g addCategoryAndPostIdFilter(array(1,2,3),array(1,3));
The following is the offical comment.
“Filters the collection by an array of post ID’s and category ID’s. When filtering by a category ID, all posts from that category will be returned. If you change the param $operator to AND, only posts that are in a category specified in $categoryIds and $postIds will be returned”
P.S. addTagIdFilter and addCategoryIdFilter function are essential function calls to addTermIdFilter() in Fishpig_Wordpress_Model_Resource_Post_Collection_Abstract with term type specified.
---------------- примеры коллекций постов -----------------
----- Посты сортированные по количеству комментов
<?php
$popular_posts = Mage::getModel('core/variable')->loadByCode('popular_posts')->getValue('html');
$popular_posts_limit = Mage::getModel('core/variable')->loadByCode('popular_posts_limit')->getValue('html');
if($popular_posts == $this->getTitle()):
$posts = Mage::getResourceModel('wordpress/post_collection')->addIsPublishedFilter('publish')->addPostTypeFilter(array('post'))->setOrderByCommentCount($dir = 'desc');
?>
<div class="block block-blog block-recent-posts">
<?php if ($title = $this->getTitle()): ?>
<div class="block-title">
<strong><span><?php echo $this->__($title) ?></span></strong>
</div>
<?php endif; ?>
<div class="block-content">
<ul id="<?php echo $this->getListId() ?>" class="info-posts">
<?php $counter = 0; foreach($posts as $post): ++$counter; ?>
<li>
<?php
$featuredImage = $post->getFeaturedImage();
if($featuredImage):
?>
<img src="<?php echo $featuredImage->_data['guid']; ?>" width="71" height="71" alt="<?php echo $this->escapeHtml($post->getPostTitle()) ?>" />
<?php endif; ?>
<div class="holder">
<h3><a href="<?php echo $post->getPermalink() ?>"><?php echo $this->htmlEscape($post->getPostTitle()) ?></a></h3>
<?php if($post->getPostExcerpt()): ?>
<p><?php echo $post->getPostExcerpt() ?></p>
<?php endif; ?>
</div>
</li>
<?php if($counter == $popular_posts_limit){ break; } endforeach; ?>
</ul>
</div>
</div>
<?php else: ?>
============================ Magento WordPress Integration ===============================
Позволяет выводить блоки Magento на страничках WP
Есть проблемы c Cookie, надо прописать в Cookie Path "/", очистсить папки var/cache, var/session, browser cache.
Очисти куки браузера!!!
http://screen.w3.ua/Nov13/8G6F43B7345QKM138.jpg
http://wordpress.org/plugins/magento-wordpress-integration/
http://www.mwi-plugin.com/documentation/default-blocks/
http://demo.mwi-plugin.com/
<?php the_block('head'); ?>
<?php the_static_block("left-customer-srvices"); ?>
=========================== Magento плагин для WP wordpress (Дает возможность использовать классы Magento в WP) ==============================
http://wordpress.org/plugins/magento/
Использует SOAP соединение, придется создать юзера и роль на бэкенде мадженты.
Вебсервере должен понимать WSDL и должно быть установлено расширение php-soap
<?php
$_product = Mage::getModel('catalog/product')->load(magento_product_id());
echo $_product->getsku();
?>
[magento pid='2, 1']
[magento cat='jeans'] = [magento cat='5']
Продукт из категории
[magento cat='jeans, 3']
Or:
[magento cat='5, 3']
Последние продукты
[magento latest='3']
Серч по имени
[magento name_like='ball, 2']
Шорткод в кастомфилде
<?php $related_products = apply_filters('the_content', html_entity_decode(get_field('related_products', get_the_ID()))); echo $related_products; ?>
Шаблон для шорткода, добавь в тему magento-products-shortcode.php (скопируй из плагина и переназови)
Пример загрузки продукта, с конфигурабл опциями в попапе с рейтингами и кастомными атрибутами.
<section class="block block-related">
<div class="block-title">
<strong><span>Related Products</span></strong>
</div>
<div class="block-content">
<ol class="mini-products-list">
<?php while(magento_have_products()): $product_id = magento_product_id(); ?>
<li class="item">
<div class="product">
<div class="product-image-box">
<?php if($product_id):
$_product = Mage::getModel('catalog/product')->load($product_id);
$special_price = Mage::helper('core')->currency($_product->getSpecialPrice());
$regular_price = Mage::helper('core')->currency($_product->getPrice());
$_helper = Mage::helper('catalog/output');
$sale = 0;
if(($_product->special_price !== null) or ($_product->_rule_price !== null))
{
$sale = 1;
}
$video = $_product->getvideo();
$maximages = 6;
if(!empty($video)){ $maximages = 4; }
$staffpick = $_product->getAttributeText('staffpick');
$newFromDate = Mage::getModel('catalog/product')->load($_product->getID())->getNewsFromDate();
$newToDate = Mage::getModel('catalog/product')->load($_product->getID())->getNewsToDate();
$now = date("Y-m-d H:m(worry)");
?>
<?php if(!empty($staffpick) && strtolower($staffpick) != 'no'): ?>
<span class="staff-pick"><?php echo __('Staff pick') ?></span>
<?php endif; ?>
<?php if($newFromDate < $now && $newToDate > $now || !empty($newFromDate) && $newFromDate < $now && empty($newToDate)): ?>
<span class="offer-box offer-new"><?php echo __('NEW!') ?></span>
<?php endif ?>
<?php if(!empty($sale)): ?>
<span class="offer-box"><?php echo __('sale!') ?></span>
<?php endif; ?>
<span class="quick-view-btn"><a class="lightbox" href="#popup<?php echo $product_id; ?>">Quick view</a></span>
<?php endif; ?>
<?php if(magento_has_image()): ?>
<a href="<?php magento_product_url(); ?>" class="product-image"><img src="<?php magento_product_thumbnail_url(); ?>" alt="image description" /></a>
<?php else: ?>
<a href="<?php magento_product_url(); ?>" class="product-image"><span class="magento-no-image"></span></a>
<?php endif; ?>
</div>
<h2 class="product-name"><a href="<?php magento_product_url(); ?>" ><?php magento_product_title(); ?></a></h2>
<?php
$special_price = Mage::helper('core')->currency($_product->getSpecialPrice());
$regular_price = Mage::helper('core')->currency($_product->getPrice());
if(($_product->special_price !== null) or ($_product->_rule_price !== null)):
?>
<div class="price-box">
<p class="special-price">
<span class="price-label"><?php echo __('Special Price'); ?>:</span>
<span class="price"><?php echo $special_price; ?></span>
</p>
<p class="old-price">
<span class="price-label"><?php echo __('Regular Price'); ?>:</span>
<span class="price"><?php echo $regular_price; ?></span>
</p>
</div>
<?php else: ?>
<div class="price-box">
<span id="product-price" class="regular-price">
<span class="price"><?php echo $regular_price; ?></span>
</span>
</div>
<?php endif; ?>
</div>
<?php if($product_id): ?>
<div class="lightbox-holder">
<div id="popup<?php echo $product_id; ?>" class="lightbox">
<div class="lightbox-frame">
<section class="product-view">
<form action="<?php echo Mage::helper('checkout/cart')->getAddUrl($_product) ?>" method="post" id="product_addtocart_form_<?php echo $_product->getId(); ?>"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
<fieldset>
<div class="no-display">
<input type="hidden" name="product" value="<?php echo $_product->getId() ?>" />
<input type="hidden" name="related_product" id="related-products-field<?php echo $_product->getId(); ?>" value="" />
</div>
<?php $_gallery = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages(); ?>
<?php $imgcount = count($_gallery); ?>
<div class="product-img-box">
<div class="product-slideshow">
<div class="slideset">
<?php if($imgcount > 0): ?>
<?php $counter = 0; foreach ($_gallery as $_image ): ++$counter; ?>
<div class="slide">
<div class="slide-holder">
<?php if(!empty($staffpick) && strtolower($staffpick) != 'no'): ?>
<span class="staff-pick"><?php echo __('Staff pick') ?></span>
<?php endif; ?>
<?php if($newFromDate < $now && $newToDate > $now || !empty($newFromDate) && $newFromDate < $now && empty($newToDate)): ?>
<span class="offer-box offer-new"><?php echo __('NEW!') ?></span>
<?php endif ?>
<?php if(!empty($sale)): ?>
<span class="offer-box"><?php echo __('sale!') ?></span>
<?php endif; ?>
<a href="<?php echo $_product->getProductUrl() ?>" class="product-image"><img src="<?php echo Mage::helper('catalog/image')->init($_product, 'small_image', $_image->getFile()); ?>" alt="<?php echo $_image->label; ?>" /></a>
</div>
</div>
<?php if($counter == $maximages){ break; } endforeach; ?>
<?php else: ?>
<div class="slide">
<div class="slide-holder">
<?php if(!empty($staffpick) && strtolower($staffpick) != 'no'): ?>
<span class="staff-pick"><?php echo __('Staff pick') ?></span>
<?php endif; ?>
<?php if($newFromDate < $now && $newToDate > $now || !empty($newFromDate) && $newFromDate < $now && empty($newToDate)): ?>
<span class="offer-box offer-new"><?php echo __('NEW!') ?></span>
<?php endif ?>
<?php if(!empty($sale)): ?>
<span class="offer-box"><?php echo __('sale!') ?></span>
<?php endif; ?>
<a href="<?php echo $_product->getProductUrl() ?>" class="product-image"><img src="<?php echo Mage::helper('catalog/image')->init($_product, 'small_image'); ?>" alt="product image" /></a>
</div>
</div>
<?php endif; ?>
</div>
<?php if($imgcount > 0): ?>
<div class="pagination-block">
<ul class="pagination">
<?php $counter = 0; foreach ($_gallery as $_image ): ++$counter; ?>
<li><a href="#"><img src="<?php echo Mage::helper('catalog/image')->init($_product, 'small_image', $_image->getFile())->resize(84,84); ?>" alt="<?php echo $_image->label; ?>" width="84" height="84" /></a></li>
<?php if($counter == $maximages){ break; } endforeach; ?>
</ul>
<?php if(!empty($video)): ?>
<div class="video-page"><a class="lightbox video-opener" href="#" data-video="<?php echo $video; ?>"><img src="<?php echo Mage::getDesign()->getSkinUrl() ; ?>images/video3.jpg" width="154" height="84" alt="image description"></a></div>
<div class="lightbox-holder">
<div class="lightbox lightbox-video">
<div class="video">
<img src="<?php echo Mage::getDesign()->getSkinUrl() ; ?>images/video4.jpg" alt="image description">
<iframe width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
</div>
<div class="product-shop">
<h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>"><?php echo $_product->getName() ?></a></h2>
<?php $sku = $_product->getSku(); if(!empty($sku)): ?><p class="availability in-stock"><?php echo __('Style#') ?> <?php echo $sku; ?></p><?php endif; ?>
<?php if($_product->isSaleable()): ?>
<p class="availability in-stock"><span><?php echo __('In stock') ?></span></p>
<?php else: ?>
<p class="availability out-of-stock"><span><?php echo __('Out of stock') ?></span></p>
<?php endif; ?>
<div class="product-price-ratings">
<?php
$special_price = Mage::helper('core')->currency($_product->getSpecialPrice());
$regular_price = Mage::helper('core')->currency($_product->getPrice());
if(($_product->special_price !== null) or ($_product->_rule_price !== null)):
?>
<div class="price-box">
<p class="special-price">
<span class="price-label"><?php echo __('Special Price'); ?>:</span>
<span class="price"><?php echo $special_price; ?></span>
</p>
<p class="old-price">
<span class="price-label"><?php echo __('Regular Price'); ?>:</span>
<span class="price"><?php echo $regular_price; ?></span>
</p>
</div>
<?php else: ?>
<div class="price-box">
<span id="product-price" class="regular-price">
<span class="price"><?php echo $regular_price; ?></span>
</span>
</div>
<?php endif; ?>
<?php
$storeId = Mage::app()->getStore()->getId();
$summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)->load($_product->getId());
if ($summaryData->getRatingSummary()):
?>
<div class="ratings">
<span class="a-left"><?php echo __('Customer Reviews'); ?>:</span>
<div class="rating-box">
<div class="rating" style="width:<?php echo $summaryData->getRatingSummary() ?>%"></div>
</div>
</div>
<?php endif;?>
</div>
<?php
$description = $_product->getdescription();
$details = $_product->getdetails();
$shipping = $_product->getshippingreturns();
$warranty = $_product->getwarranty();
if(!empty($description) || !empty($details) || !empty($shipping) || !empty($warranty)):
?>
<ul class="product-accordion">
<?php if(!empty($description)): ?>
<li class="active">
<a class="opener" href="#"><?php echo __('Product Story'); ?> <span class="arrow"><?php echo __('arrow'); ?></span></a>
<div class="slide">
<p><?php echo $description; ?></p>
</div>
</li>
<?php endif; ?>
<?php if(!empty($details)): ?>
<li <?php if(empty($description)): ?>class="active"<?php endif; ?>>
<a class="opener" href="#"><?php echo __('Details & Care'); ?> <span class="arrow"><?php echo __('arrow'); ?></span></a>
<div class="slide">
<p><?php echo $details; ?></p>
</div>
</li>
<?php endif; ?>
<?php if(!empty($shipping)): ?>
<li <?php if(empty($description) && empty($details)): ?>class="active"<?php endif; ?>>
<a class="opener" href="#"><?php echo __('Shipping & Returns'); ?> <span class="arrow"><?php echo __('arrow'); ?></span></a>
<div class="slide">
<p><?php echo $shipping; ?></p>
</div>
</li>
<?php endif; ?>
<?php if(!empty($warranty)): ?>
<li <?php if(empty($shipping) && empty($description) && empty($details)): ?>class="active"<?php endif; ?>>
<a class="opener" href="#"><?php echo __('Warranty'); ?> <span class="arrow"><?php echo __('arrow'); ?></span></a>
<div class="slide">
<p><?php echo $warranty; ?></p>
</div>
</li>
<?php endif; ?>
</ul>
<?php endif; ?>
<div class="product-shop-holder">
<div class="column-l">
<div id="product-options-wrapper" class="product-options">
<?php if($_product->getTypeId() == "configurable"): ?>
<?php $attValConfig = $_product->getTypeInstance()->getConfigurableAttributesAsArray(); ?>
<?php if(sizeof($attValConfig)): ?>
<?php foreach($attValConfig as $attValConfigSingle): ?>
<div class="<?php echo strtolower($attValConfigSingle['label']); ?>-options">
<label class="required"><em>*</em><?php echo $attValConfigSingle['label']; ?>:</label>
<div class="input-box input-box-select">
<select name="super_attribute[<?php echo $attValConfigSingle['attribute_id'] ?>]" id="attribute<?php echo $_product->getId() ?>" class="required-entry super-attribute-select">
<?php foreach($attValConfigSingle['values'] as $attValConfigSingleVal): ?>
<option value="<?php echo $attValConfigSingleVal['value_index'] ?>"><?php echo $attValConfigSingleVal['label'] ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
<?php endif; ?>
</div>
<meta property="og:image" content="<?php echo Mage::helper('catalog/image')->init($_product, 'thumbnail')->resize(210,210); ?>" />
<link rel="image_src" href="<?php echo Mage::helper('catalog/image')->init($_product, 'thumbnail')->resize(210,210); ?>" />
<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
<script type="text/javascript">stLight.options({publisher: "53875c69-490e-4fdc-88e8-0bb167809031", doNotHash: false, doNotCopy: false, hashAddressBar: false});</script>
<script type="text/javascript">stLight.options({publisher: "ur-8840f22a-19c6-b21f-b953-89c7b7d7adc7", doNotHash: false, doNotCopy: false, hashAddressBar: false});</script>
<ul class="social">
<li><span class='st_facebook_large' displayText='Facebook'></span></li>
<li><span class='st_twitter_large' displayText='Tweet'></span></li>
<li><span class='st_pinterest_large' displayText='Pinterest'></span></li>
<li><span class='st_instagram_large' displayText='Instagram Badge'></span></li>
<li><a class="email" href="<?php echo $_product->getProductUrl() ?>"><?php echo __('email'); ?></a></li>
</ul>
</div>
<div class="column-r">
<div class="product-options-bottom">
<?php if($_product->isSaleable()): ?>
<div class="add-to-cart">
<div class="add-to-cart-row">
<div class="qty-box">
<label for="qty<?php echo $_product->getId(); ?>"><?php echo __('Quantity'); ?>:</label>
<div class="input-text-qty"><input name="qty" id="qty<?php echo $_product->getId(); ?>" maxlength="12" placeholder="1" title="<?php echo __('Quantity'); ?>" class="input-text qty" type="text"></div>
<input type="submit" class="no-display" value="Sub"/>
</div>
</div>
<div class="add-to-cart-row">
<button type="button" class="button add-to-basket-link" onclick="product_addtocart_form_<?php echo $_product->getId() ?>.submit()">
<span><span><?php echo __('Add to Basket'); ?></span></span>
</button>
</div>
</div>
<?php else: ?>
<span class="additions-out"><?php echo __('Sorry! The product is currently out of stock'); ?></span>
<?php endif; ?>
<?php $_wishlistSubmitUrl = Mage::helper('wishlist')->getAddUrl($_product); ?>
<?php if (Mage::helper('wishlist')->isAllow()) : ?>
<ul class="add-to-links">
<li><a href="<?php echo $_wishlistSubmitUrl ?>" onclick="productAddToCartForm.submitLight(this, '<?php echo $_wishlistSubmitUrl ?>'); return false;" class="link-wishlist"><?php echo __('Add to Wishlist') ?></a></li>
</ul>
<?php endif; ?>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</section>
<a class="view-link" href="<?php echo $_product->getProductUrl() ?>"><?php echo __('View full details'); ?></a>
</div>
</div>
</div>
<?php endif; ?>
</li>
<?php endwhile; ?>
</ol>
</div>
</section>
以上是关于text Magento WordPress集成的主要内容,如果未能解决你的问题,请参考以下文章
如何将 Magento 客户授权令牌从 php curl 传递到浏览器?
wordpress fishpig magento 安装 - getPostListHtml()