Timber plugin with term (WordPress) - wordpress

I have a list of posts with one term assigned for one post.
I have 5 terms. I generated a list of the term used. I would like to display only post with the same term in my archive page.
archive.php :
$templates = array( 'archive.twig', 'index.twig' );
$context = Timber::get_context();
$context['categories'] = Timber::get_terms('category', array('hide_empty' => true));
$context['title'] = 'Archive';
if ( is_day() ) {
$context['title'] = 'Archive: '.get_the_date( 'D M Y' );
} else if ( is_month() ) {
$context['title'] = 'Archive: '.get_the_date( 'M Y' );
} else if ( is_year() ) {
$context['title'] = 'Archive: '.get_the_date( 'Y' );
} else if ( is_tag() ) {
$context['title'] = single_tag_title( '', false );
} else if ( is_category() ) {
$context['title'] = single_cat_title( '', false );
array_unshift( $templates, 'archive-' . get_query_var( 'cat' ) . '.twig' );
} else if ( is_post_type_archive() ) {
$context['title'] = post_type_archive_title( '', false );
array_unshift( $templates, 'archive-' . get_post_type() . '.twig' );
}
$context['posts'] = Timber::get_posts();
Timber::render( $templates, $context );
In my home.twig file where all post are display :
<ul class="category--list">
{% for cat in categories %}
<li>{{cat.name}}</li>
{% endfor %}
</ul>
What loop must I create in my "archive.twig" file to only display post in a term clicked ?

#Jardon, first step is to get the relevant term...
archive.php
$context['term'] = new Timber\Term();
//this will fetch whichever term is in the scope of that php file
then you just need to send it over to the twig file for display...
archive.twig
<h2>{{ term.name }}</h2>

Related

Woocommerce recently viewed Products

I have created a recently viewed script which generated a shortcode which I then inserted into my home page.
The script is designed so that people who may have visited my website and left, once they come back can see instantly what products they had been viewing on their last visit.
I have placed the shortcode [woocommerce_recently_viewed_products]
and have generated the shortcode using the following script:
function rc_woocommerce_recently_viewed_products( $atts, $content = null ) {
// Get shortcode parameters
extract(shortcode_atts(array(
"per_page" => '5'
), $atts));
// Get WooCommerce Global
global $woocommerce;
// Get recently viewed product cookies data
$viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', $_COOKIE['woocommerce_recently_viewed'] ) : array();
$viewed_products = array_filter( array_map( 'absint', $viewed_products ) );
// If no data, quit
if ( empty( $viewed_products ) )
return __( 'You have not viewed any product yet!', 'rc_wc_rvp' );
// Create the object
ob_start();
wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) );
}
// Get products per page
if( !isset( $per_page ) ? $number = 4 : $number = $per_page )
// Create query arguments array
$query_args = array(
'posts_per_page' => $number,
'no_found_rows' => 1,
'post_status' => 'publish',
'post_type' => 'product',
'post__in' => $viewed_products,
'orderby' => 'rand'
);
// Add meta_query to query args
$query_args['meta_query'] = array();
// Check products stock status
$query_args['meta_query'][] = $woocommerce->query->stock_status_meta_query();
// Create a new query
$r = new WP_Query($query_args);
// If query return results
if ( $r->have_posts() ) {
$content = '<ul class="rc_wc_rvp_product_list_widget">';
// Start the loop
while ( $r->have_posts()) {
$r->the_post();
global $product;
$content .= '<li>
<a href="' . get_permalink() . '">
' . ( has_post_thumbnail() ? get_the_post_thumbnail( $r->post->ID, 'shop_thumbnail' ) : woocommerce_placeholder_img( 'shop_thumbnail' ) ) . ' ' . get_the_title() . '
</a> ' . $product->get_price_html() . '
</li>';
}
$content .= '</ul>';
}
// Get clean object
$content .= ob_get_clean();
// Return whole content
return $content;
}
// Register the shortcode
add_shortcode("woocommerce_recently_viewed_products",
"rc_woocommerce_recently_viewed_products");
Everything seems to have registered. However,when I test this myself. I view a few products, go back to the homepage where the shortcode is registered and I see the text
You have not viewed any product yet!
I can not figure out what might be missing in order to register and show the products which I or a potential customer may have viewed.
Woocommerce only save the recently viewed cookie IF woocommerce_recently_viewed_products WIDGET is ACTIVE! See code in wc-product-functions.php wc_track_product_view() function.
Code to save the cookie always in functions.php:
/**
* Track product views. Always.
*/
function wc_track_product_view_always() {
if ( ! is_singular( 'product' ) /* xnagyg: remove this condition to run: || ! is_active_widget( false, false, 'woocommerce_recently_viewed_products', true )*/ ) {
return;
}
global $post;
if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) ) { // #codingStandardsIgnoreLine.
$viewed_products = array();
} else {
$viewed_products = wp_parse_id_list( (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) ); // #codingStandardsIgnoreLine.
}
// Unset if already in viewed products list.
$keys = array_flip( $viewed_products );
if ( isset( $keys[ $post->ID ] ) ) {
unset( $viewed_products[ $keys[ $post->ID ] ] );
}
$viewed_products[] = $post->ID;
if ( count( $viewed_products ) > 15 ) {
array_shift( $viewed_products );
}
// Store for session only.
wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) );
}
remove_action('template_redirect', 'wc_track_product_view', 20);
add_action( 'template_redirect', 'wc_track_product_view_always', 20 );
You need to set the cookie when you are viewing a single product page so use something like this where I set the cookie to equal the product ID I just viewed. In your case you'll need to get the cookie value if it exists then append the new product to the list of products.
function set_user_visited_product_cookie() {
global $post;
if ( is_product() ){
// manipulate your cookie string here, explode, implode functions
wc_setcookie( 'woocommerce_recently_viewed', $post->ID );
}
}
add_action( 'wp', 'set_user_visited_product_cookie' );
Below code to set cookie 'woocommerce_recently_viewed' worked for me. Hope it helps other
$Existing_product_id = $_COOKIE['woocommerce_recently_viewed'];
if ( is_product() )
{
$updated_product_id = $Existing_product_id.'|'.$post->ID;
wc_setcookie( 'woocommerce_recently_viewed', $updated_product_id );
}

Cannot get custom taxonomy filter in media list view to work

I have created a filter dropdown in Media list view to filter media files based on selected term. The dropdown rendered OK with the custom taxonomy item. But the filter is not working at all. Irrespective of the term I select from this dropdown, all media items are being listed. No filtration is happening.
Here is my code to create the filter dropdown (in functions.php):
function media_add_content_category_filter_dropdown()
{
$scr = get_current_screen();
if ( $scr->base !== 'upload' ) return;
$terms = get_terms('media_content_category', array('hide_empty' => false));
if ( $terms ) {
printf( '<select name="%s" class="postform">', esc_attr( 'mcfdd' ) );
print( '<option value="">All Categories</option>');
foreach ( $terms as $term ) {
printf( '<option value="%s">%s</option>', esc_attr( $term->term_id ), esc_html( $term->name ) );
}
print( '</select>' );
}
}
add_action('restrict_manage_posts', 'media_add_content_category_filter_dropdown');
And this is the code I am using to for filtration purpose:
function media_content_filter($query) {
if ( is_admin() && $query->is_main_query() ) {
if (isset($_GET['mcfdd']) && $_GET['mcfdd'] == -1) {
$query->set('mcfdd', '');
}
}
}
add_action('pre_get_posts','media_content_filter');
Working solution to display taxonomy filters on media library and filter:
//[[START] - Add custom taxonomy dropdown to media library
function media_add_content_category_filter_dropdown()
{
global $wp_query;
// check we're in the right place, otherwise return
if ( 'upload.php' != $pagenow )
return;
$tax_slug = 'media_content_category';
$tax_obj = get_taxonomy( $tax_slug );
// check if anything has been selected, else set selected to null
$selected = isset($wp_query->query[$tax_slug]) ? $wp_query->query[$tax_slug] : null;
wp_dropdown_categories( array(
'show_option_all' => __($tax_obj->label . ' - All'),
'taxonomy' => $tax_slug,
'name' => $tax_obj->name,
'orderby' => 'name',
'selected' => $selected,
'hierarchical' => true,
// 'show_count' => true,
'hide_empty' => false
) );
}
add_action('restrict_manage_posts', 'media_add_content_category_filter_dropdown');
To filter posts by custom taxonomy
function media_tsm_post_convert_id_to_term_in_query($query)
{
global $pagenow, $typenow;
// check we're in the right place, otherwise return
if ( 'upload.php' != $pagenow )
return;
$filters = get_object_taxonomies( $typenow );
foreach ( $filters as $tax_slug ) {
$var = &$query->query_vars[$tax_slug];
if ( $var != 0 ) {
$term = get_term_by( 'id', $var, $tax_slug );
$var = $term->slug;
}
}
}
add_filter('parse_query', 'media_tsm_post_convert_id_to_term_in_query');
//[END] - Add custom taxonomy dropdown to media library

How to make custom form-tag in contact form 7 required

So i make custom form-tag in contact form 7! It is a drop down with list of my courses and now I want to make it required because that is the main thing in whole form.
So can someone give me a tip how to do that?
When I do the [myCustomField* course-name class:custom-field]
It does not working with *
So if someone can help it will be great!
I have been working on this myself this afternoon and I do not think Mahmoud has added everything that is needed to get the validation working well and the messages showing up.
using what I have learnt from the posts on contact form 7 here:
https://contactform7.com/2015/01/10/adding-a-custom-form-tag
https://contactform7.com/2015/02/27/using-values-from-a-form-tag/
and looking at this file in the plugin: contact-form-7/modules/select.php which helped a lot.
I think this will work better and needs to be added to your functions.php file in your child-theme.
add_action( 'wpcf7_init', 'custom_add_form_tag_myCustomField' );
function custom_add_form_tag_myCustomField() {
wpcf7_add_form_tag( array( 'myCustomField', 'myCustomField*' ),
'custom_myCustomField_form_tag_handler', true );
}
function custom_myCustomField_form_tag_handler( $tag ) {
$tag = new WPCF7_FormTag( $tag );
if ( empty( $tag->name ) ) {
return '';
}
$validation_error = wpcf7_get_validation_error( $tag->name );
$class = wpcf7_form_controls_class( $tag->type );
if ( $validation_error ) {
$class .= ' wpcf7-not-valid';
}
$atts = array();
$atts['class'] = $tag->get_class_option( $class );
$atts['id'] = $tag->get_id_option();
if ( $tag->is_required() ) {
$atts['aria-required'] = 'true';
}
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
$atts['name'] = $tag->name;
$atts = wpcf7_format_atts( $atts );
$myCustomField = '';
$query = new WP_Query(array(
'post_type' => 'CUSTOM POST TYPE HERE',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
));
while ($query->have_posts()) {
$query->the_post();
$post_title = get_the_title();
$myCustomField .= sprintf( '<option value="%1$s">%1$s</option>',
esc_html( $post_title ) );
}
wp_reset_query();
$myCustomField = sprintf(
'<span class="wpcf7-form-control-wrap %1$s"><select %2$s>%3$s</select>%4$s</span>',
sanitize_html_class( $tag->name ),
$atts,
$myCustomField,
$validation_error
);
return $myCustomField;
}
That is how we create the custom tag. The important differences here are the addition of the $validation_error variables as wells the aria-required and aria-invalid data. It is also important to include the $validation_error in the final output so that we can see the validation messages being created.
Then to finish it off we need to add some validation via filters.
There is no documentation on this yet, but I used the functions from the select.php and altered them to what I needed.
/* Validation filter */
add_filter( 'wpcf7_validate_myCustomField', 'wpcf7_myCustomField_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_myCustomField*', 'wpcf7_myCustomField_validation_filter', 10, 2 );
function wpcf7_myCustomField_validation_filter( $result, $tag ) {
$tag = new WPCF7_FormTag( $tag );
$name = $tag->name;
if ( isset( $_POST[$name] ) && is_array( $_POST[$name] ) ) {
foreach ( $_POST[$name] as $key => $value ) {
if ( '' === $value ) {
unset( $_POST[$name][$key] );
}
}
}
$empty = ! isset( $_POST[$name] ) || empty( $_POST[$name] ) && '0' !== $_POST[$name];
if ( $tag->is_required() && $empty ) {
$result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
}
return $result;
}
This code should also go in your functions.php file just under the code for the custom CF7 tag.
Here the filter's first string $tag should match with the class that is being generated in the custom CF7 tag so if your custom tag->type = 'myCustomField' then the $tag of the filter must include the name, like so wpcf7_validate_myCustomField as well as the required version of it, wpcf7_validate_myCustomField*.
I hope that helps anyone else looking for this.
If you want even more of the options available from the backend of Contact Form 7 check the select.php file as it lays it out quite nicely on how to get each option and include it.
You can use [select*] to output a required drop-down menu.
[select* course-name include_blank "English" "Math"]
Check https://contactform7.com/checkboxes-radio-buttons-and-menus/
EDIT:
So you have your own shortcode [myCustomField]. To make two versions of your shortcode as [myCustomField] and [myCustomField*] you have to pass both shortcodes to your function as the following:
add_action( 'wpcf7_init', 'wpcf7_add_form_tag_mycustomfield' );
function wpcf7_add_form_tag_mycustomfield() {
wpcf7_add_form_tag( array( 'myCustomField', 'myCustomField*'),
'wpcf7_mycustomfield_form_tag_handler', array( 'name-attr' => true ) );
}
function wpcf7_mycustomfield_form_tag_handler( $tag ) {
$tag = new WPCF7_FormTag( $tag );
if ( empty( $tag->name ) ) {
return '';
}
$atts = array();
$class = wpcf7_form_controls_class( $tag->type );
$atts['class'] = $tag->get_class_option( $class );
$atts['id'] = $tag->get_id_option();
$atts['name'] = $tag->name;
$atts = wpcf7_format_atts( $atts );
$html = sprintf( '<your-tag %s></your-tag>', $atts );
return $html;
}
Then, you can use it:
[myCustomField course-name class:custom-field]
or
[myCustomField* course-name class:custom-field]
References:
https://contactform7.com/2015/01/10/adding-a-custom-form-tag
https://contactform7.com/2015/02/27/using-values-from-a-form-tag/

Wordpress Deleting downloaded images on metabox with file

require_once(ABSPATH . '/wp-load.php');
require_once(ABSPATH . '/wp-admin/includes/file.php');
require_once(ABSPATH . '/wp-admin/includes/image.php');
$upload_overrides = array( 'test_form' => FALSE );
$count_files = count( $_FILES['my_files'] );
$uploads = wp_upload_dir();
foreach ( range( 0, $count_files ) as $i ) {
// create an array of the $_FILES for each file
$file_array = array(
'name' => $_FILES['files']['name'][$i],
'type' => $_FILES['files']['type'][$i],
'tmp_name' => $_FILES['files']['tmp_name'][$i],
'error' => $_FILES['files']['error'][$i],
'size' => $_FILES['files']['size'][$i],
);
// check to see if the file name is not empty
if ( !empty( $file_array['name'] ) ) {
// upload the file to the server
$uploaded_file = wp_handle_upload( $file_array, $upload_overrides );
// checks the file type and stores in in a variable
$wp_filetype = wp_check_filetype( basename( $uploaded_file['file'] ), null );
if ( $uploaded_file && !isset( $uploaded_file['error'] ) ) {
$ufiles = get_post_meta( $post_id, 'my_files', true );
if( empty( $ufiles ) ) $ufiles = array();
$ufiles[] = $uploaded_file;
update_post_meta( $post_id, 'my_files', $ufiles );
}
}
}
I am able to download files to metabox thanks to this code.
Output of the database is looks like what i show in the below
a:2:{i:0;a:3:{s:4:"file";s:48:"D:xampphtdocswp/wp-content/uploads/2016/08/2.jpg";s:3:"url";s:52:"http://localhost/wp/wp-content/uploads/2016/08/2.jpg";s:4:"type";s:10:"image/jpeg";}i:1;a:3:{s:4:"file";s:59:"D:xampphtdocswp/wp-content/uploads/2016/08/2da83a4s-960.jpg";s:3:"url";s:63:"http://localhost/wp/wp-content/uploads/2016/08/2da83a4s-960.jpg";s:4:"type";s:10:"image/jpeg";}}
I want to delete the images that i dont want with delete_post_meta method while i am selecting checkboxes on my update page.
$galleri = get_post_meta($id,'my_files',true);
<div class="galeri">
<?php
foreach($galleri as $galeri){
echo "<div style='margin:10px;display:inline-block;'><input type='checkbox' name='car_image_delete[]' value='".$galeri['url']."' /><img src='".$galeri['url']."' width='150' height='150'/></div>";
}
?>
</div>
I appreciate if you help me
Try this:
Use update_post_meta() function instead of delete_post_meta().
While using delete_post_meta(), it will delete custom fields.
So if you want to delete particular one file. You need to use update_post_meta().
$string = 'a:2:{i:0;a:3:{s:4:"file";s:48:"D:xampphtdocswp/wp-content/uploads/2016/08/2.jpg";s:3:"url";s:52:"http://localhost/wp/wp-content/uploads/2016/08/2.jpg";s:4:"type";s:10:"image/jpeg";}i:1;a:3:{s:4:"file";s:59:"D:xampphtdocswp/wp-content/uploads/2016/08/2da83a4s-960.jpg";s:3:"url";s:63:"http://localhost/wp/wp-content/uploads/2016/08/2da83a4s-960.jpg";s:4:"type";s:10:"image/jpeg";}}';
$arr = unserialize($string); //USE get_post_meta() function instead of
$index = array_search('http://localhost/wp/wp-content/uploads/2016/08/2da83a4s-960.jpg',array_column( $arr, 'url')); //search index
echo $index;
if (array_key_exists($index,$arr))
{
unset($arr[$index]); //remove array index
}
print_r($arr); //array with only value.
//use array_values() to reindex
update_post_meta($post_id, 'my_files', $arr); //update post meta

Custom upload directory to also change attachment meta

Please see below the filter I am using to change the upload directory for my custom post-type.
My custom post-type name is 'download'
My new directory for uploads in my custom post-type 'download' is now... wp-content/downloads/
The problem is in doing this, is that I my image thumbnails are missing because the attachment meta data is looking for the thumbnail in the original directory wp-content/uploads/.
How can I adjust my filter or fix the problem so the attachment data for this custom post-type only uses the new directory wp-content/downloads/
Thanks is advance for any advice or help.
Josh
add_filter( 'upload_dir', 'my_custom_upload_dir' );
function my_custom_upload_dir( $default_dir ) {
if ( ! isset( $_POST['post_id'] ) || $_POST['post_id'] < 0 )
return $default_dir;
if ( get_post_type( $_POST['post_id'] ) != 'download' )
return $default_dir;
$dir = WP_CONTENT_DIR . '/downloads';
$url = WP_CONTENT_URL . '/downloads';
$bdir = $dir;
$burl = $url;
$subdir = '';
if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
$time = current_time( 'mysql' );
$y = substr( $time, 0, 4 );
$m = substr( $time, 5, 2 );
$subdir = "/$y/$m";
}
$dir .= $subdir;
$url .= $subdir;
$custom_dir = array(
'path' => $dir,
'url' => $url,
'subdir' => $subdir,
'basedir' => $bdir,
'baseurl' => $burl,
'error' => false,
);
return $custom_dir;
}
you could make custom posttype templates, and in those code custom get attachmentfunctions.
http://codex.wordpress.org/Post_Type_Templates
this custom code could look for the post_meta key: _wp_attached_file.
<?php $attachment_file = get_post_meta($current_post_id, '_wp_attached_file', false); ?>
http://codex.wordpress.org/Function_Reference/get_post_meta

Resources