I have ACF field for Tribe events category.
Can't find the solution for showing the field in Tribe events template. This is my code below:
<?php
$event_id = get_the_ID();
$event_cats = get_the_terms($event_id, 'tribe_events_cat');
$custom_field = get_field( 'custom_field', Tribe__Events__Main::TAXONOMY );
foreach ($event_cats as $category) {
echo '<p>' . $category->name . '</p>';
echo '<p>' . $custom_field . '</p>';
}
?>
UPDATE===
Add a function to functions.php
if ( class_exists('Tribe__Events__Main') ){
function tribe_get_color_categories ( $event_id = null ) {
if ( is_null( $event_id ) ) {
$event_id = get_the_ID();
}
$event_cats = '';
$term_list = wp_get_post_terms( $event_id, Tribe__Events__Main::TAXONOMY );
foreach( $term_list as $term_single ) {
$category_color_primary = get_field('event_category_color', $term_single);
}
if($category_color_primary) {
echo 'style="color:';
echo $category_color_primary;
echo ' " ';
}
}
}
And then call it on the template
<div <?php echo tribe_get_color_categories (); ?>>Some text</div>
Related
I am setting up a custom post with a front-office display filter via taxonomy. After several hours of research and tests, I finally managed to get what I want but I still have 2 little things on which I am stuck... I would have liked to add an ALL button to re-display all my archives if we clicked on another filter before.
I also can’t add a class to my filter button when it is activated... Do you have a lead to refer me please?
Below what I did:
archive-work.php
<div id="work-filter" class="col-md-12">
<?php get_work_filters(); ?>
</div>
<div class="work-results animated fadeIn">
<?php $res = my_get_posts();
echo $res['response']; ?>
</div>
functions.php
/***************** filter work ****************/
function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', get_template_directory_uri() .
'/assets/js/work.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
$result = array();
// Script for getting posts
function ajax_filter_get_posts( $work_item ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) ||
!wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ))
die('Permission denied');
$work_item = $_POST['expertises'];
$result = json_encode(my_get_posts($work_item, true));
echo $result;
die();
}
function my_get_posts($work_item = '', $ajax = false){
// WP Query
$args = array(
'expertises' => $work_item,
'post_type' => 'work',
'posts_per_page' => -1,
);
// If taxonomy is not set, remove key from array and get all posts
if( !$work_item ) {
unset( $args['expertises'] );
}
$query = new WP_Query( $args );
$html = '';
$items = array();
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
$res = '<div class="works">'.
'<a href="'.get_permalink().'">'.
'<article class="panel panel-default" id="post-'.get_the_id().'">'.
'<div class="panel-body">'.
'<div class="panel-cover">'.
'<h3>'.get_the_title().'</h3>'.
get_the_excerpt().
'</div>'.
'<div class="imgworkarch">'.
get_the_post_thumbnail( $post = null, $size = 'archivework' ).
'</div>'.
'</div>'.
'</article>'.
'</a>' .
'</div>';
$ajax ? $items[] = $res : $html .= $res;
endwhile;
$result['response'] = $ajax ? $items : $html;
$result['status'] = 'success';
else:
$result['response'] = '<h2>No posts found</h2>';
$result['status'] = '404';
endif;
wp_reset_postdata();
return $result;
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
//Get Work Filters
function get_work_filters()
{
$work_items = get_terms('expertises');
$filters_html = false;
$count = count( $work_items );
if( $count > 0 ):
foreach( $work_items as $work_item )
{
$work_item_id = $work_item->term_id;
$work_item_name = $work_item->name;
$filters_html .= '<a href="' .
get_term_link( $work_item ) .
'" class="btn work-filter" title="' .
$work_item->slug . '">' . $work_item->name . '</a> ';
}
echo $filters_html;
endif;
}
work.js
$(document).ready(function(){
// work filters
$('.work-filter').click( function(event) {
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var expertises = $(this).attr('title');
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
post_type: "work", // selected tag
expertises: expertises,
};
$.ajax({
type: "post",
dataType: "json",
url: afp_vars.afp_ajax_url,
data: data,
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
// Restore div visibility
$('.work-results').fadeOut()
.queue(function(n) {
$(this).html(data.response);
n();
}).fadeIn();
},
error: function( XMLHttpRequest, textStatus, errorThrown ) {
/*console.log( MLHttpRequest );
console.log( textStatus );
console.log( errorThrown );*/
$('.work-results').fadeOut()
.queue(function(n) {
$(this).html("No items found. ");
n();
}).fadeIn();
}
});
});
});
Maybe it's too late to answer this, but I hope it helps someone.
You just have to add another button into your work-filter block with a different title like 'reset', then remove the taxonomy filter on the query in your my_get_posts when the value matches the title. Here is the code:
function my_get_posts($taxonomy = '', $ajax = false)
{
if($taxonomy != 'reset'){
$args = array(
'service' => $taxonomy,
'post_type' => 'projects',
'posts_per_page' => -1,
);
}else{
$args = array(
'post_type' => 'projects',
'posts_per_page' => -1,
);
}
if (!$taxonomy) {
unset($args['service']);
}
$query = new WP_Query($args);
$html = '';
$items = array();
if ($query->have_posts()) :
while ($query->have_posts()) :
$query->the_post();
$res = '<div class="col-lg-4">' .
'<a href="' . get_permalink() . '">' .
'<article class="panel panel-default" id="post-' . get_the_id() . '">' .
'<div class="panel-body">' .
get_the_post_thumbnail() .
'<div class="panel-cover">' .
'<h3>' . get_the_title() . '</h3>' .
get_the_content() .
'</div>' .
'</div>' .
'</article>' .
'</a>' .
'</div>';
$ajax ? $items[] = $res : $html .= $res;
endwhile;
$result['response'] = $ajax ? $items : $html;
$result['status'] = 'success';
else :
$result['response'] = '<h2>No posts found</h2>';
$result['status'] = '404';
endif;
wp_reset_postdata();
return $result;
}
function reset_all(){
echo 'All ';
}
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app("default");
$orderNumber = 260038;
$order = Mage::getModel('sales/order')->loadByIncrementId($orderNumber);
foreach ($order->getAllItems() as $item){
$productOptions = $item->getProductOptions();
echo $product_id = $item->product_id;
$_product=Mage::getModel('catalog/product')->load($product_id);
if ($_product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
if (isset($productOptions['bundle_options']))
{
foreach ($productOptions['bundle_options'] as $productOption)
{
echo $value = $productOption['value'][0]['title'];
echo ' || ';
echo $value = $productOption['value'][0]['qty'];
echo ' || ';
echo $value = $productOption['value'][0]['price'];
echo "<br>";
}
}
}
}
I am able to get the title, qty and the price of product, I also want to get the product SKU.
Bundle products can have options, options can have selections. This is 'two-tier' structure. If you just want to get all selections without options, you can use something like this:
$selections = $product->getTypeInstance(true)
->getSelectionsCollection($product->getTypeInstance(true)
->getOptionsIds($product), $product);
foreach($selections as $selection){
echo $selection->getSku();
}
But if you want get full information about options and their selections, use next way (based on your example):
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app("default");
$orderNumber = 260038;
$order = Mage::getModel('sales/order')->loadByIncrementId($orderNumber);
$store_id = $order->getStoreId();
foreach ($order->getAllItems() as $item){
$product = Mage::getModel('catalog/product')->setStoreId($store_id)->load($item->product_id);
$options = Mage::getModel('bundle/option')->getResourceCollection()
->setProductIdFilter($item->product_id)
->setPositionOrder();
$options->joinValues($store_id);
$selections = $product->getTypeInstance(true)
->getSelectionsCollection($product->getTypeInstance(true)
->getOptionsIds($product), $product);
foreach ($options->getItems() as $option) {
$option_id = $option->getId();
echo 'Option: ' . $option->getTitle() . ' [id: ' . $option_id . ']<br />';
foreach($selections as $selection){
if($option_id == $selection->getOptionId()){
$selection_id = $selection->getId();
$selection_name = $selection->getName();
$selection_qty = $selection->getSelectionQty();
$selection_sku = $selection->getSku();
$selection_product_id = $selection->getProductId();
$selection_weight = $selection->getWeight();
$selection_price = $selection->getPrice();
$data = 'Selection Name: ' . $selection_name;
$data .= ', SKU: ' . $selection_sku;
$data .= ', Qty: ' . $selection_qty;
$data .= ', ID: ' . $selection_id;
$data .= ', Product ID: ' . $selection_product_id;
$data .= ', Weight: ' . $selection_weight;
$data .= ', Price: ' . $selection_price;
echo $data . '<br />';
}
}
}
}
?>
Here we go,
To get product sku by selected option id:
$optionId = "selected option id";
$bundleTable = Mage::getSingleton('core/resource')->getTableName('catalog_product_bundle_selection');
$collection=Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect(array('name', 'price'));
$collection->getSelect()->joinLeft(array('bundleselect'=> $bundleTable),"entity_id = bundleselect.product_id","product_id");
$collection->getSelect()->where(" bundleselect.selection_id IN (".$optionId.") " );
$origPrice = '0';
foreach($collection as $prod) {
$origPrice += $prod->getSku();
}
echo $origSku;
Magento 2 get bundle options with their selections details.
Class BundleItemDetails
public function __construct(
\Magento\Catalog\Model\ProductRepository; $productRepository
)
{
$this->productRepository = $productRepository;
}
public function execute(){
$product = $this->productRepository->get("test-bundle-product");
$optionsCollection = $product->getTypeInstance(true)
->getOptionsCollection($product);
$optionDetails = [];
foreach ($optionsCollection as $option){
$selections = $product->getTypeInstance(true)
->getSelectionsCollection(
$option->getOptionId(),$product
);
//selection details by optionids
foreach ($selections as $selection) {
$optionDetails[$option->getOptionId()] = $selection->getSku();
}
}
}
}
I'm using the CI Calendar. The db that I've connected it with has columns for: date, hours, category, and notes. I started out with the same format as in this tutorial from net tuts+. I can get the calendar to display the notes on the appropriate day, but I'm not sure how to split up the content section into hours, category and notes. I know I have to modify the generate calendar in the system file, but not sure how to do it.
Here's my code:
Controller:
function index($year = null, $month = null)
{
if (!$year) {
$year = date('Y');
}
if (!$month) {
$month = date('m');
}
$this->load->model('calendar_model');
if ($day = $this->input->post('day')) {
$this->calendar_model->add_calendar_data(
"$year-$month-$day",
$this->input->post('hours'),
$this->input->post('category'),
$this->input->post('notes')
);
}
$data['calendar'] = $this->calendar_model->generate($year, $month);
// Load a view in the content partial
$this->template->content->view('includes/user_navigation');
$this->template->content->view('dashboard', $data);
// Display the template
$this->template->publish();
}
Model:
<?php
class Calendar_model extends CI_Model {
var $conf;
function Calendar_model()
{
parent::__construct();
}
function get_calendar_data($year, $month) {
$query = $this->db->select()->from('calendar')
->like('date', "$year-$month", 'after')->get();
$cal_data = array();
foreach ($query->result() as $row) {
$cal_data[substr($row->date,8,2)] = $row->notes;
/* Testing purposes */
echo "<p>" . $row->date . "</p>";
echo"<p>" . $row->hours . "</p>";
echo "<p>" . $row->category . "</p>";
echo "<p>" . $row->notes . "</p>";
}
return $cal_data;
}
function add_calendar_data($date, $hours, $category, $notes) {
if ($this->db->select('date')->from('calendar')
->where('date', $date)->count_all_results()) {
$this->db->where('date', $date)
->update('calendar', array(
'date' => $date,
'hours' => $hours,
'category' => $category,
'notes' => $notes
));
} else {
$this->db->insert('calendar', array(
'date' => $date,
'hours' => $hours,
'category' => $category,
'notes' => $notes
));
}
}
function generate ($year, $month) {
$this->load->library('calendar');
$cal_data = $this->get_calendar_data($year, $month);
return $this->calendar->generate($year, $month, $cal_data);
}
}
Calendar template:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Calendar configuration
|--------------------------------------------------------------------------
| This file will contain the settings for the calendar template library.
|
*/
$config['day_type'] = 'long';
$config['show_next_prev'] = true;
$config['next_prev_url'] = base_url('index.php/calendar/display');
$config['template'] = '
{table_open}
<table class="calendar">
{/table_open}
{heading_row_start}<tr>{/heading_row_start}
{heading_previous_cell}<th><<</th>{/heading_previous_cell}
{heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
{heading_next_cell}<th>>></th>{/heading_next_cell}
{heading_row_end}</tr>{/heading_row_end}
{week_day_cell}
<th class="day_header">{week_day}</th>
{/week_day_cell}
{cal_row_start}<tr class="days">{/cal_row_start}
{cal_cell_start}<td class="day">{/cal_cell_start}
{cal_cell_content}
<div class="day_num">{day}</div>
<div class="content">
<div class="category">{category}
<div class="hours">{hours}
<div class="notes">{notes}
{content}
</div>
</div>
</div>
</div>
{/cal_cell_content}
{cal_cell_content_today}
<div class="today"><div class="day_num">{day}</div>
<div class="content">{content}</div></div>
{/cal_cell_content_today}
{cal_cell_no_content}
<div class="day_num">{day}</div>
{/cal_cell_no_content}
{cal_cell_no_content_today}
<div class="today"><div class="day_num">{day}</div></div>
{/cal_cell_no_content_today}
';
js code in my view:
$(document).ready(function(){
var date;
// === Prepare calendar === //
$('.calendar .day').click(function() {
day_num = $(this).find('.day_num').html();
$("#activityModal").modal('toggle');
$('#add-event-submit').click(function(){
var hrs = document.getElementById('activityHrs').value;
var note = document.getElementById('activityNotes').value;
var cat = document.getElementById('activityCats');
var selectedCat = cat.options[cat.selectedIndex].text;
var message = "Date: " + date + "\n";
message += "hrs: " + hrs + "\n";
message += "category: " + selectedCat + "\n";
message += "note: " + note;
message += "day num: " + day_num;
//alert(message);
if (hrs != null && selectedCat !=null && note !=null) {
$.ajax({
url: window.location,
type: 'POST',
data: {
day: day_num,
hours: hrs,
category: selectedCat,
notes: note
},
success: function(msg) {
location.reload();
}
});
}
});
});
});
I am just learning to create meta box to upload file in wp-content/uploads folder through below code:
//display image meta box
function display_image_box() {
global $post;
wp_nonce_field( plugin_basename( __FILE__ ), 'wp_custom_noncename' );
echo '<input id="post_media" type="file" name="post_media" value="" size="25" />';
}
//upload image
function update_custom_meta_data( $id, $data_key, $is_file = false ) {
global $post;
if( $is_file && ! empty( $_FILES ) ) {
$upload = wp_handle_upload( $_FILES[$data_key], array( 'test_form' => false ) );
if( isset( $upload['error'] ) && '0' != $upload['error'] ) {
wp_die( 'There was an error uploading your file. ' );
} else {
update_post_meta( $id, $data_key, $upload );
}
}
}
//save image
function save_custom_meta_data( $id ) {
if( ! wp_verify_nonce( $_POST['wp_custom_noncename'], plugin_basename( __FILE__ ) ) ) {
return;
}
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
update_custom_meta_data( $id, 'post_media', true );
}
add_action( 'save_post', 'save_custom_meta_data' );
//register script
function register_admin_scripts() {
wp_register_script( 'custom_admin_script', get_template_directory_uri() . '/js/admin.js' );
wp_enqueue_script( 'custom_admin_script' );
}
add_action( 'admin_enqueue_scripts', 'register_admin_scripts' );
this working & uploaded file nicely but i cant display it cause getting the array something like this:
> [post_media] => Array
(
[0] => a:3:{s:4:"file";s:81:"E:wampwwwtestchild/wp-content/themes/twentyeleven/uploads/2012/12/coffee_star.jpg";s:3:"url";s:60:"wp-content/themes/twentyeleven/image/2012/12/coffee_star.jpg";s:4:"type";s:10:"image/jpeg";}
)
so how can i display the image file now ?
Since the custom fields are saved in _postmeta table, we will get it by $post->ID.
$media = stripslashes(get_post_meta($post->ID, 'post_media', true));
if (isset($media[0])){
echo '<img src="'.$media.'" alt="images" />';
}
Hope it helps...
And if you want to try this code.
Upload Script
<script type="text/javascript">
var formfield = '';
$j(document).ready(function(){uploadimagebutton();});
function uploadimagebutton() {
$j('#upload_image_button').click(function() {
formfield = $j(this).prev().attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
if (formfield) {
imgurl = $j(html).attr('src');
$j('#'+formfield).val(imgurl);
tb_remove();
$j('#pagebackgroundthumb').html('<img src="'+imgurl+'" alt="" style="max-width:85%;" />');
} else {
window.original_send_to_editor(html);
}
};
$j('#delete_image_button').click(function(){
formfield = $j(this).prev().prev().attr('name');
$j('#'+formfield).attr('value', '');
$j('#pagebackgroundthumb').html('');
});
}
</script>
place this in your theme function.php
<?php
/* -------------------------------------------------------------
Meta boxes
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
add_action('edit_post', 'adj_update');
add_action('save_post', 'adj_update');
add_action('publish_post', 'adj_update');
/* Use the admin_menu action to define the custom boxes */
add_action('admin_menu', 'adj_add_custom_box');
/* Adds a custom section to the "advanced" Post and Page edit screens */
function adj_add_custom_box() {
if( function_exists( 'add_meta_box' )) {
add_meta_box( 'addsettings', 'Additional Settings',
'adj_inner_custom_box', 'page', 'advanced', 'high' );
}
}
/* Prints the inner fields for the custom post/page section */
function adj_inner_custom_box() {
// Use nonce for verification
echo '<input type="hidden" name="myplugin_noncename" id="myplugin_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// The actual fields for data entry
global $post;
$subtitle = stripslashes(get_post_meta($post->ID, 'subtitle', true));
$pagebackground = stripslashes(get_post_meta($post->ID, 'pagebackground', true));
?>
<div class="inside">
<label for="subtitle"><strong>Page Subtitle:</strong> </label>
<input type="text" name="subtitle" value="<?php echo $subtitle ?>" id="subtitle" style="width:95%" />
<p>If menu title is different with page title, please type here the desired page title.</p>
<label for="pagebackgroundthumb"><strong>Page Background Image:</strong> </label>
<div id="pagebackgroundthumb"><?php if(!empty($pagebackground))echo '<img src="'.$pagebackground.'" alt="" width="80%" />';?></div>
<input id="upload_image" name="pagebackground" type="hidden" size="45" value="<?php echo $pagebackground;?>">
<input class="button-secondary" id="upload_image_button" value="Upload/Select an image" type="button"><input class="button-secondary" id="delete_image_button" value="Delete" type="button">
</div>
<?php
}
function adj_update($id) {
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
return $post_id;
}
$label = $_POST['subtitle'];
$pagebackground = $_POST['pagebackground'];
if (!empty($label)) {
$meta_value = get_post_meta($id, 'subtitle', true);
if(!empty($meta_value)) {
update_post_meta($id, 'subtitle', $label);
} else {
add_post_meta($id, 'subtitle', $label, true);
}
} else {
delete_post_meta($id, 'subtitle');
}
if (!empty($pagebackground)) {
$meta_value = get_post_meta($id, 'pagebackground', true);
if(!empty($meta_value)) {
update_post_meta($id, 'pagebackground', $pagebackground);
} else {
add_post_meta($id, 'pagebackground', $pagebackground, true);
}
} else {
delete_post_meta($id, 'pagebackground');
}
}
?>
<?php $currentCat = Mage::registry('current_category');
if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
{
$loadCategory = $currentCat;
}
else
{
$loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
}
$subCategories = explode(',', $loadCategory->getChildren());
foreach ( $subCategories as $subCategoryId )
{
$cat = Mage::getModel('catalog/category')->load($subCategoryId);
if($cat->getIsActive())
{
if ($currentCat->getEntityId() == $subCategoryId)
{
echo '<b>'.$cat->getName().'</b><br />';
}
else
{
echo ''.$cat->getName().' ('.$cat->getProductCount().')<br />';
}
}
}
?>