I am pretty new to php and having a little trouble figuring out what I am doing wrong. For some reason kd_mfi_the_featured_image( 'featured-image-3', 'post' ); dose not exists (even though It upload and looks fine in the word press admin panel) so it dose not = true and it will not display.
The goal is to display featured-image-3 of all the child pages only if featured-image-3 exists ( I am using this plugin to have multiple featured images). My method is as follows
Get current page ID
Us current page ID to query child pages
If there are child pages setup post data for each child page
Check to see if the child page has featured-image-3
If child page has featured_image-3 display it : If not query next post
Code in customPage.php
<?php if ( have_posts() ) { /* Query and display the parent. */
while ( have_posts() ) {
the_post();
the_content();
$thispage=$post->ID;
}
} ?>
<?php $childpages = query_posts('post_type=page&post_parent='.$thispage);
if($childpages) /* display the children content */
foreach ($childpages as $post) :
setup_postdata($post);
if (kd_mfi_the_featured_image( 'featured-image-3', 'post' )) {
kd_mfi_the_featured_image( 'featured-image-3', 'post' );
the_post_thumbnail();
}
else {
$wp_query->next_post();
}
endforeach; ?>
Code in Functions.php
if( class_exists( 'kdMultipleFeaturedImages' ) ) {
$args2 = array(
'id' => 'featured-image-2',
'post_type' => 'page', // Set this to post or page
'labels' => array(
'name' => 'Home Page Carousel',
'set' => 'Set Home Page Carousel',
'remove' => 'Remove Home Page Carousel',
'use' => 'Use as Home Page Carousel',
)
);
$args3 = array(
'id' => 'featured-image-3',
'post_type' => 'page', // Set this to post or page
'labels' => array(
'name' => 'Product Category Hero',
'set' => 'Set Product Category Hero',
'remove' => 'Remove Product Category Hero',
'use' => 'Use as Product Category Hero',
)
);
$args4 = array(
'id' => 'featured-image-4',
'post_type' => 'page', // Set this to post or page
'labels' => array(
'name' => 'Product Category Featured',
'set' => 'Set Product Category Featured',
'remove' => 'Remove Product Category Featured',
'use' => 'Use as Product Category Featured',
)
);
new kdMultipleFeaturedImages( $args2);
new kdMultipleFeaturedImages( $args3 );
new kdMultipleFeaturedImages( $args4 );
}
Related
On my product detail page I'm trying to allow users to add multiple cross-sell products to the cart at once.
I found a few examples how this could be done. But most of them work with URL parameters.
For my case I'm trying to do this with ajax. Like the default add-to-cart button.
On my research I found an example here.
But I'm not sure how to adapt it for my case.
At the moment I have a list of product ID's from a custom loop.
Here's my custom loop code:
add_action('woocommerce_single_product_cols_before', 'show_cross_sell_in_single_product', 1200);
function show_cross_sell_in_single_product(){
$crosssells = get_post_meta( get_the_ID(), '_crosssell_ids',true);
$args = array(
'post_type' => 'product',
'posts_per_page'=> -1,
'post__in' => $crosssells,
'tax_query' => array(
array(
'relation' => 'OR',
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => 'NOT IN',
),
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => '=',
),
)
),
);
$products_crosssells = new WP_Query( $args );
$products_crosssells_ids = wp_list_pluck( $products_crosssells->posts, 'ID' );
if( $products_crosssells->have_posts() ) : ?>
<div>
<ul>
<?php while ( $products_crosssells->have_posts() ) : $products_crosssells->the_post(); ?>
<?php wc_get_template_part( 'content', 'product-crosssells' ); ?>
<?php endwhile; ?>
</ul>
Add all to the cart
</div>
<?php endif;
wp_reset_postdata();
}
The product ID's are stored in $products_crosssells_ids.
As I understand the example from the link above, I need to add the product ID's to the custom function:
add_action('wp_ajax_multi_add_to_cart', 'multi_ajax_add_to_cart');
add_action('wp_ajax_nopriv_multi_add_to_cart', 'multi_ajax_add_to_cart');
function multi_ajax_add_to_cart() {
if (isset($_POST['items']) ) {
$item_keys = array();
foreach( $_POST['items'] as $item ) {
if( isset($item['id']) ) {
$item_qty = isset($item['qty']) && $item['qty'] > 1 ? $item['qty'] : 1;
$item_keys[] = WC()->cart->add_to_cart($item['id'], $item_qty);
}
}
echo json_encode($item_keys); // Send back cart item keys
}
die();
}
But I'm not sure how I need to add/adapt this code to my product page.
So A user could click on this link and adds everything to the cart:
Add all to the cart
Im trying to filter my custom post types by a checkbox field of ACF.
I work with this tutorial: https://www.advancedcustomfields.com/resources/creating-wp-archive-custom-field-filter/
Now I got the problem that nothing change, when ich filter over the checkboxes on the archive page of the custom post type. It generates only the right URL but doesn't filter the posts.
Does some have any idea why?
function.php:
// array of filters (field key => field name)
$GLOBALS['my_query_filters'] = array(
'mitglieder' => 'mitglieder'
);
// action
function my_pre_get_posts( $query ) {
// bail early if is in admin
if( is_admin() ) return;
// bail early if not main query
// - allows custom code / plugins to continue working
if( !$query->is_main_query() ) return;
// get meta query
$meta_query = $query->get('meta_query');
// loop over filters
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: http://www.website.com/events?city=melbourne,sydney
$value = explode(',', $_GET[ $name ]);
// append meta query
$meta_query = array(
array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
)
);
}
// update meta query
$query->set('meta_query', $meta_query );
}
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
register_taxonomy_for_object_type('category', 'projekte'); // Register Taxonomies for Category
$labels = array(
'name' => __('Projekte', 'projekte'), // Rename these to suit
'singular_name' => __('Projekt', 'projekte'),
'add_new' => __('Projekt hinzufügen', 'projekte'),
'add_new_item' => __('Neues Projekt hinzufügen', 'projekte'),
'edit' => __('Bearbeiten', 'projekte'),
'edit_item' => __('Projekt bearbeiten', 'projekte'),
'new_item' => __('Neues Projekt', 'projekte'),
'view' => __('Anschauen', 'projekte'),
'view_item' => __('Projekt anschauen', 'projekte'),
'search_items' => __('Projekte durchsuchen', 'projekte'),
'not_found' => __('Projekt wurde nicht gefunden', 'projekte'),
'not_found_in_trash' => __('Projekt wurde nicht im Papierkorb gefunden', 'projekte')
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'hierarchical' => true, // Allows your posts to behave like Hierarchy Pages
'has_archive' => true,
'supports' => array(
'title',
'excerpt'
), // Go to Dashboard Custom HTML5 Blank post for supports
'can_export' => true, // Allows export in Tools > Export
'taxonomies' => array(
'category',
) // Add Category and Post Tags support
);
register_post_type('projekte', $args);
archive-projekte.php:
<div id="archive-filters">
<?php foreach( $GLOBALS['my_query_filters'] as $key => $name ):
// get the field's settings without attempting to load a value
$field = get_field_object($key, false, false);
// set value if available
if( isset($_GET[ $name ]) ) {
$field['value'] = explode(',', $_GET[ $name ]);
}
// create filter
?>
<div class="filter" data-filter="<?php echo $name; ?>">
<?php create_field( $field ); ?>
</div>
<?php endforeach; ?>
</div>
<script type="text/javascript">
(function($) {
// change
$('#archive-filters').on('change', 'input[type="checkbox"]', function(){
// vars
var url = '<?php echo home_url('projekte'); ?>';
args = {};
// loop over filters
$('#archive-filters .filter').each(function(){
// vars
var filter = $(this).data('filter'),
vals = [];
// find checked inputs
$(this).find('input:checked').each(function(){
vals.push( $(this).val() );
});
// append to args
args[ filter ] = vals.join(',');
});
// update url
url += '?';
// loop over args
$.each(args, function( name, value ){
url += name + '=' + value + '&';
});
// remove last &
url = url.slice(0, -1);
// reload page
window.location.replace( url );
});
$('.button.acf-add-checkbox').parent().remove();
})(jQuery);
</script>
<div class="projekt-archive">
<?php
$args = array(
'post_type' => 'projekte',
'post_status' => 'publish',
'posts_per_page' => '-1'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : ?>
......
<?php
endwhile;
endif;
?>
<?php wp_reset_query(); ?>
I used your code to try and recreate your issue and ran into a number of issues but got it working. On the link you supplied the video tutorial does things differently to the sample code.
The first thing I noticed is that you are changing the $query in the functions then redefining it in archive-projekte.php
$args = array(
'post_type' => 'projekte',
'post_status' => 'publish',
'posts_per_page' => '-1'
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) :
//......
endwhile;
endif;
wp_reset_query();
you can just use a version of the standard loop instead
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//.......
}
}
Secondly when I set the advanced custom field(mitglieder) in Wordpress admin to be a checkbox it is then rendered as a checkbox on the front end by create_field() in the filter div but the problem is that checkboxes are saved in the meta data as serialized data so it didn't work so I changed the advanced custom field to a radio button it all works fine.
The new issue created by this is that the filter div now has radio buttons. So I watched the video tutorial and output checkboxes using a foreach loop on $field instead of using create_field, this means that the javascript needs to be changed also.
Now the only issue remains is if you need you advanced custom field to be checkbox sothat one of your projekte posts to have more than one mitglieder value then you would need to work with the serialized meta data in order to make the filter work correctly.
This works like ACF example video which uses houses and bedrooms and in that case a house cannot be a 2 bedroom house and a 3 bedroom house at the same time.
I have an URL like this:
example.com/movies/157336/Interstellar
For reference:
example.com/movies/%movie_id%/%movie_name%
Please note, the movie_id is a custom field, and not the actual post ID.
The movie_name is the post title slug, but is only there for SEO reasons.
I need WordPress to load the page based on the custom field movie_id found in the URL and not use the page name, and if the movie_id is not found, throw the regular 404 error.
The main problem I am having, is that I can’t seem to get WordPress to load a page based on the custom field movie_id from the URL, it always uses movie_name as reference point.
How do I know that? Well the correct URL would be example.com/movies/157336/Interstellar and if I change the title to example.com/movies/157336/Intersterlarxyz then WordPress gives a 404 error.
And if I change the ID but leave the movie name correct, like this: example.com/movies/123/Interstellar then WordPress still loads the correct page.
Based on this behavior, it's safe to say WordPress loads the page based on the page slug from the URL, rather than the movie ID, and that is what I need to fix.
Here is my code so far:
movie-plugin.php
// Register Custom Post Type "movies"
function register_moviedb_post_type() {
register_post_type( 'movies',
array(
'labels' => array(
'name' => __( 'Movies' ),
'singular_name' => __( 'Movies' )
),
'taxonomies' => array('category'),
'public' => true,
'has_archive' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => 'movies','with_front' => FALSE),
'supports' => array( 'title', 'editor', 'custom-fields','comments','page-attributes','trackbacks','revisions', 'thumbnail')
)
);
flush_rewrite_rules();
}
add_action( 'init', 'register_moviedb_post_type' );
// Add custom rewrite tag 'movie_id'
function custom_rewrite_tag() {
add_rewrite_tag('%movie_id%', '([^/]+)', 'movie_id=');
}
add_action('init', 'custom_rewrite_tag');
// Add rewrite rule
function custom_rewrite_basic() {
add_rewrite_rule(
'^movies/([^/]*)/([^/]*)/?',
//'index.php?post_type=movies&movie_id=$matches[1]',
'index.php?post_type=movies&movie_id=$matches[1]&name=$matches[2]',
'top'
);
}
add_action('init', 'custom_rewrite_basic');
// Query var 'movie_id'
function add_query_vars_filter( $vars ){
$vars[] = "movie_id";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
// Custom Page Template
function custom_movie_page_template() {
if ( is_singular( 'movies' ) ) {
add_filter( 'template_include', function() {
return plugin_dir_path( __FILE__ ) . '/movies.php';
});
}
}
add_action( 'template_redirect', 'custom_movie_page_template' );
// Create custom post type link for movies
function movie_post_type_link( $link, $post = 0 ){
if ( $post->post_type == 'movies' ){
$id = $post->ID;
$post = &get_post($id);
$movie_id = get_post_meta($post->ID,'movie_id', true);
empty ( $post->slug )
and $post->slug = sanitize_title_with_dashes( $post->post_title );
return home_url(
user_trailingslashit( "movies/$movie_id/$post->slug" )
);
} else {
return $link;
}
}
add_filter( 'post_type_link', movie_post_type_link, 1, 2 );
If I remove the movie_name from the URL in add_rewrite_rule, WordPress just loads the archive page of that post type.
'index.php?post_type=movies&movie_id=$matches[1]',
If I use the page name in the URL rewrite, it always loads the page based on the name, rather than the movie_id.
'index.php?post_type=movies&movie_id=$matches[1]&name=$matches[2]',
I didn't test code below, but movies.php could be like this:
<?php $movieId = (int)get_query_var('movie_id') ;
if(movieId ==! 0):
$args = array(
'post_type' => 'movies',
'posts_per_page' => 1,
'meta_key' => 'movie_id',
'meta_value' => $movieId
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
//code that display data
<?php endwhile; else : ?>
//code to create post
<?php endif;
else:
//normal loop
endif;
Having a bit of bother with the Wordpress Meta Box plugin, specifically with retrieving an image url from an image added to a custom post type.
I'm creating meta boxes in a custom plugin, like so:
add_filter( 'rwmb_meta_boxes', 'xxx_meta_register_meta_boxes' );
function xxx_meta_register_meta_boxes( $meta_boxes )
{
$prefix = 'xxx_meta_';
$meta_boxes[] = array(
'title' => esc_html__( 'Retailer Information', '' ),
'id' => 'advanced',
'post_types' => array( 'xxx_retailers' ),
'autosave' => true,
'fields' => array(
// PLUPLOAD IMAGE UPLOAD (WP 3.3+)
array(
'name' => esc_html__( 'Retailer Logo', '' ),
'id' => "{$prefix}plupload",
'type' => 'plupload_image',
'max_file_uploads' => 1,
),
// URL
array(
'name' => esc_html__( 'Link', '' ),
'id' => "{$prefix}url",
'desc' => esc_html__( 'Clicking the retailer logo will take the user to this URL', '' ),
'type' => 'url',
'std' => 'xxx',
),
)
);
return $meta_boxes;
}
So far so good, these boxes are relevant to a custom post type 'xxx_retailers'.
The problem comes with retrieving this data. I want to display my retailers in a widget. I've chopped and changed another piece of code I've used previously, but it's not returning the image URL, just the ID. Unfortunately I don't know enough php to figure out why.
// Create Retailers Widget
// Create the widget
class Retailers_Widget extends WP_Widget {
function __construct() {
parent::__construct(
// base ID of the widget
'retailers_widget',
// name of the widget
__('XXX Retailers List', '' ),
// widget options
array (
'description' => __( 'Shows a list of retailer logos', '' )
)
);
}
function widget( $args, $instance ) {
// kick things off
extract( $args );
echo $before_widget;
echo $before_title . 'Retailers' . $after_title;
// Pull through Retailers
$xxxretailers = get_posts(array(
'post_type' => 'xxx_retailers',
'orderby' => 'title',
'order' => 'asc',
));
// Display for each Retailer
foreach ($xxxretailers as $xxxretailer) {
$custom = get_post_custom($xxxretailer->ID);
$meta_ret_img = $custom["xxx_meta_plupload"][0];
$meta_ret_url = $custom["xxx_meta_url"][0];
// Display Retailers
echo "<li><a href='{$meta_ret_url}'><img src='{$meta_ret_img}' /></a></li>";
}
}
};
// Register widget
function register_retailers_widget() {
register_widget( 'Retailers_Widget' );
}
add_action( 'widgets_init', 'register_retailers_widget' );
The URLs are coming through correctly, so I know this is a problem with the line
$meta_ret_img = $custom["xxx_meta_plupload"][0];
But I can't figure out how to get the image URL from the data I presume is stored as an array. Any ideas?
Edit:
I should have mentioned, in a single post I can get a single image with:
$images = rwmb_meta( 'xxx_meta_plupload', 'size=medium' );
if ( !empty( $images ) ) {
foreach ( $images as $image ) {
echo "<img src='{$image['url']}' />";
}
}
But I want to show images from all my retailers post types, to create a list of logos.
Replace this statement:
$meta_ret_img = $custom["xxx_meta_plupload"][0];
with this:
$meta_ret_img_array = wp_get_attachment_image_src($custom["xxx_meta_plupload"][0]);
$meta_ret_img = $meta_ret_img_array[0];
also please remove all these curly braces from src and href attributes from your code.
if you are interested in any particular size of the image, then see the official document of wp_get_attachment_image_src() function here.
For e.g. for medium size image you can write it as:
wp_get_attachment_image_src($custom["xxx_meta_plupload"][0], 'medium');
I am working on a post_type and taxonomy. I create a page template "foo_template.php" for its main page, in main page I write a query that shows all taxonomies and related (5) Five posts. When i click on any taxonomy the new page open and it shows all post titles of clicked taxonomy and its slug is "foo_taxonomy", i also create for it a page "taxonomy-foo_post.php" and when i click any title it goes on single page which i created for it "single-foo_post.php" and its slug is "foo_post".
Now the main issue is i want that post type and taxonomy slug is same when i do this my page layout is disturbed and it goes to archive.php
My friend give me some code i write it, where post_type and taxonomy slug is same, when i click on the taxonomy the page open with new same slug but when i click on the post title for single page it shows that "Page not found"
What is the issue i don't get it.
Here is my code:
Post type and Taxonomy code:
add_action('init', 'foo_articles');
function foo_articles() {
register_post_type('foo_knowledgebase', array(
'labels' => array(
'name' => 'Articles',
'singular_name' => 'Article'
),
'public' => true,
'rewrite' => array(
'slug' => 'My_slug')
));
}
add_action( 'init', 'foo_taxonomies', 0 );
function foo_taxonomies() {
register_taxonomy('foo_taxonomy', array('My_slug'), array(
'labels' => array(
'name' => 'Articles Category'
),
'show_ui' => true,
'show_admin_column' => true,
'show_tagcloud' => FALSE,
'hierarchical' => true,
'rewrite' => array('slug' => 'My_slug', 'with_front' => TRUE)
));
}
For same slug code:
$rules = array();
$taxonomies = get_taxonomies(array('_builtin' => false), 'objects');
$post_types = get_post_types(array('public' => true, '_builtin' => false), 'names');
foreach ($post_types as $post_type) {
$post_type_data = get_post_type_object( $post_type );
$post_type_slug = $post_type_data->rewrite['slug'];
foreach ($taxonomies as $taxonomy) {
if ($taxonomy->object_type[0] == $post_type_slug) {
$categories = get_categories(array('type' => $post_type_slug, 'taxonomy' => $taxonomy->name, 'hide_empty' => 0));
/* #var $category type */
foreach ($categories as $category) {
$rules[$post_type_slug . '/' . $category->slug . '/?$'] = 'index.php?' . $category->taxonomy . '=' . $category->slug;
}
}
}
}
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter( 'generate_rewrite_rules', 'taxonomy_slug_rewrite' );
My friend said that this code work for him but i dont now what happen here i copied same code.
This condition is also set true
if ($taxonomy->object_type[0] == $post_type_slug)
but i don't know why my slug not work.
Please help me
For what you want to achieve you will need to define the Custom Taxonomy BEFORE the Custom Post Type.
This way will work but in the unlikely event that your Taxonomy and your Post will have the same slug won't be able to view the entry.
e.g. if you will have a taxonomy term called "press" and a CPT with the title "press".