Anchor links in a WooCommerce categories widget - wordpress

I use a code that displays products under each category on the archive page /shop:
Category 1
product 1 product 2 product 3
Category 2
product 1 product 2 product 3
Here is my code:
<?php
foreach( get_terms( array( 'taxonomy' => 'product_cat' ) ) as $category ) :
$products_loop = new WP_Query( array(
'post_type' => 'product',
'showposts' => -1,
'tax_query' => array_merge( array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'terms' => array( $category->term_id ),
'field' => 'term_id'
)
), WC()->query->get_tax_query() ),
'meta_query' => array_merge( array(
// You can optionally add extra meta queries here
), WC()->query->get_meta_query() )
) );
?>
<h2 class="category-title"><?php echo $category->name; ?></h2>
<?php
while ( $products_loop->have_posts() ) {
$products_loop->the_post();
/**
* woocommerce_shop_loop hook.
*
* #hooked WC_Structured_Data::generate_product_data() - 10
*/
do_action( 'woocommerce_shop_loop' );
wc_get_template_part( 'content', 'product' );
}
wp_reset_postdata(); ?>
<?php endforeach; ?>
I also use a standard widget to display WooCommerce categories. As I understand it, the file is responsible for it - woocommerce / includes / widget / class-wc-widget-product-categories.php.
How can I modify this file (code for functions.php) to add anchor links? For example, in the categories menu, I select Category 2 and the page moves down to Category 2 with its products.
I just can’t find a ready-made solution, so I ask you for help. I hope this code will be useful to other users.

You need to add some javascript and add "data-link" attribute with a href for category term in your code
<h2 class="category-title" data-link="<?php echo get_term_link( (int) $category->term_id, 'product_cat' ); ?>"><?php echo $category->name; ?></h2>
I created a snippet to demonstrate:
$('.product-categories .cat-item > a').on('click', function(e) {
e.preventDefault();
var href = $(this).attr('href');
$('html, body').animate({
scrollTop: $("[data-link='" + href + "']").offset().top
}, 1000);
});
.left {
float: left;
width: 50%;
}
.right {
float: right;
width: 50%;
}
.category-wrapper {
height: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="left">
<ul class="product-categories">
<li class="cat-item">
Category 1
</li>
<li class="cat-item">
Category 2
</li>
</ul>
</div>
<div class="right">
<div class="category-wrapper">
<h2 class="category-title" data-link="http://category1">Category 1</h2>
</div>
<div class="category-wrapper">
<h2 class="category-title" data-link="http://category2">Category 2</h2>
</div>
</div>

Related

How can I add custom class to menu item in WordPress. Below is my code, it does not work

header.php
/*Render menu*/
<div class="main-nav">
<?php wp_nav_menu(
array(
'theme_location' => 'header-menu',
'container' => 'ul',
'menu_class' => 'nav'
)
);
?>
</div>
functions.php
/*Register menu*/
function register_main_menu(){
register_nav_menus(array(
'Primary' => __('Header Menu'),
'Footer' => __('Footer Menu')
));
}
add_action('after_setup_theme', 'register_main_menu');
/*Custom menu class*/
function add_class_to_li($classes, $item){
$classes[] = "nav-item";
return $classes;
}
add_filter('nav_menu_css_class','add_class_to_li', 10, 4);
This does not add 'nav-item' class to 'li'. Is there anything that I need to update.
Your theme_location should be exactly like the one you have in your functions.php file. So your reader menu will be:
/*Render menu*/
<div class="main-nav">
<?php wp_nav_menu(
array(
'theme_location' => 'Primary', //this will be Primary, not header-menu
'container' => 'ul',
'menu_class' => 'nav'
)
);
?>
</div>

Display all categories in WP, with the selected in bold

I want to display all the categories existing in my Wordpress in the bottom of the content, with the selected for the current post in bold, as follows.
For example, for an existing post I selected category2 of 3 existing.
category1 category2 category3
How can I do this?
My code (now only display the selected category):
<div class="entry-meta">
<span class="term-links">
<?php foreach ( get_the_terms( $post->ID, 'category') as $term ) :
?>
<a href="<?php echo esc_url( get_term_link( $term->term_id ) )
?>"><span class="<?php echo $term->slug ?>"><?php echo $term->name ?>
</span></a>
<?php endforeach; ?>
</span>
<style>
.term-links .category2 {
display: inline-block;
font-weight:bold;
</style>
list of all category
add below code in your template
<style type="text/css">
.single-product div.product .product_meta .product_cat ul li{ list-style-type:circle;}
.single-product div.product .product_meta .product_cat ul li.current-cat{list-style-type:circle;}
.single-product div.product .product_meta .product_cat ul li.current-cat a{display: inline-block;font-weight:bold;}
</style>
<?php
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
$product_cat_id_array = array();
foreach ($terms as $term ) {
$product_cat_id_array[] = $term->term_id;
}
$product_cat_id_string = implode(",",$product_cat_id_array);
$args = array(
'child_of' => 0,
'current_category' => $product_cat_id_string,
'depth' => 0,
'echo' => 1,
'exclude' => '',
'exclude_tree' => '',
'feed' => '',
'feed_image' => '',
'feed_type' => '',
'hide_empty' => 0,
'hide_title_if_empty' => false,
'hierarchical' => true,
'order' => 'ASC',
'orderby' => 'name',
'separator' => '',
'show_count' => 0,
'show_option_all' => '',
'show_option_none' => __( 'No categories' ),
'style' => 'list',
'taxonomy' => 'product_cat',
'title_li' => __( 'Categories' ),
'use_desc_for_title' => 0,
);
wp_list_categories($args);
?>

How to display "full" image URL so I can have a random background in Wordpress

I am trying to write a custom page type that gives a page a random background in Wordpress. (i.e nice big image on the homepage). I have got it working! But am returning a large image, any ideas how to quickly add make it display the full image size URL?
Help much appreciated!
(I have stuck the full code in so anyone can use it on their own sites if it helps?)
<?php
/**
* Template Name: Fullscreen Random
*/
get_header();
?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<style media="screen" type="text/css">
body {
background: url(<?php
$args = array( 'post_type' => 'attachment', 'numberposts' => 1, 'orderby' => 'rand', 'post_status' => null, 'post_parent' => 5 );
$attachments = get_posts( $args );
if ($attachments) {
foreach ( $attachments as $attachment ) {
echo $attachment->guid;
}
}
?>) no-repeat center center fixed;
webkit-background-size: cover;
moz-background-size: cover;
o-background-size: cover;
background-size: cover;
}
#menu {background:rgba(0, 0, 0, 0.2)!important;}
* {color:white!important;}
</style>
<?php endwhile; ?>
<? get_footer(); ?>
Using wp_attachment_is_image to make sure you're getting only your images and wp_get_attachment_image_src with the attachment id and "full" as parameters you can get the url for the full-size attachment image from the first element of the returned array (haven't tested this but it seems viable).
For those interested in the final script with #"Edgar Allan Pwn" suggestion incorporated it is below:
<?php
/**
* Template Name: Fullscreen Random
*/
get_header();
?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<style media="screen" type="text/css">
body {
background: url(<?php
$args = array(
'orderby' => 'rand',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => 1,
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) { ?>
<?php $full = wp_get_attachment_image_src( $attachment->ID, 'full', false, false );
echo $full[0];
}
}
?>) no-repeat center center fixed;
webkit-background-size: cover;
moz-background-size: cover;
o-background-size: cover;
background-size: cover;
}
#menu {background:rgba(0, 0, 0, 0.2)!important;}
* {color:white!important;}
</style>
<?php endwhile; ?>
<? get_footer(); ?>

Alphabetical list/index for custom tags -> even if empty - Wordpress

In wordpress (3.4) I created some code which returns an alphabetical list/index of custom tags and filters the custom posts in a grid layout. The tags are named as "tagdirectory". The custom post is named "directory".
This is the code:
<?php $list = '';
$tags = get_terms( 'tagdirectory' );
echo '<ul id="portfolio-filter">';
echo'<li>All</li>';
$groups = array();
if( $tags && is_array( $tags ) ) {
foreach( $tags as $tag ) {
$first_letter = strtoupper( $tag->name[0] );
$groups[ $first_letter ][] = $tag;}
if( !empty( $groups ) ) {
foreach( $groups as $letter => $tags ) {
$list .= "\n\t" . '<h2>' . apply_filters( 'the_title', $letter ) .'</h2>';
$list .= "\n\t" . '<ul>';
foreach( $tags as $tag ) {
$lower = strtolower($tag->name);
$name = str_replace(' ', ' ', $tag->name);
$naam = str_replace(' ', '-', $lower);
$list .= "\n\t\t" . '<li>'.$name.'</li>';
}}}}else $list .= "\n\t" . '<p>Sorry, but no tags were found</p>';print $list;
echo "</ul>";
?>
This works perfectly but I would also like for empty letters from the alphabet to be shown.
For example, now it returns:
A
Aicher Otl
Apeloig Philippe
B
Bass Saul
F
Fitszimmons Maureen
... and so on
But it doesn't show the empty letter groups because there are no tags starting with this letter. I do need it to show the capital letter for empty groups though, like so:
A
Aicher Otl
Apeloig Philippe
B
Bass Saul
C
D
E
F
Fitszimmons Maureen
G
... and so on
Can anybody help me and tell me what code I should add for this to work?
Thanks!
I have just edited this solution> http://wordpress.mcdspot.com/2010/12/03/template-to-list-posts-by-first-letter-of-title/
I got it to display a custom post type by changing the 'post-type' on line #37 to the correct custom taxonomy ('distributors' as I am using to list companies by name) and it's done the trick.
Here is the code:
<?php
/*
Template Name: A-Z Pages
A WordPress template to list page titles by first letter.
You should modify the CSS to suit your theme and place it in its proper file.
Be sure to set the $posts_per_row and $posts_per_page variables.
*/
$posts_per_row = 3;
$posts_per_page = 15;
?>
<?php get_header(); ?>
<style type="text/css">
.letter-group { width: 100%; }
.letter-cell { width: 5%; height: 2em; text-align: center; padding-top: 8px; margin-bottom: 8px; background: #e0e0e0; float: left; }
.row-cells { width: 70%; float: right; margin-right: 180px; }
.title-cell { width: 30%; float: left; overflow: hidden; margin-bottom: 8px; }
.clear { clear: both; }
</style>
<div id="main-background">
<div id="main-column">
<h1><?php the_title(); ?></h1>
<div class="margin-top"></div>
<div id="a-z">
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array (
'posts_per_page' => $posts_per_page,
'post_type' => 'page',
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged
);
query_posts($args);
if ( have_posts() ) {
$in_this_row = 0;
while ( have_posts() ) {
the_post();
$first_letter = strtoupper(substr(apply_filters('the_title',$post->post_title),0,1));
if ($first_letter != $curr_letter) {
if (++$post_count > 1) {
end_prev_letter();
}
start_new_letter($first_letter);
$curr_letter = $first_letter;
}
if (++$in_this_row > $posts_per_row) {
end_prev_row();
start_new_row();
++$in_this_row; // Account for this first post
} ?>
<div class="title-cell"><?php the_title(); ?></div>
<?php }
end_prev_letter();
?>
<div class="navigation">
<div class="alignleft"><?php next_posts_link('« Higher Letters') ?></div>
<div class="alignright"><?php previous_posts_link('Lower Letters »') ?></div>
</div>
<?php } else {
echo "<h2>Sorry, no posts were found!</h2>";
}
?>
</div><!-- End id='a-z' -->
</div><!-- End class='margin-top -->
</div><!-- End id='rightcolumn' -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
<?php
function end_prev_letter() {
end_prev_row();
echo "</div><!-- End of letter-group -->\n";
echo "<div class='clear'></div>\n";
}
function start_new_letter($letter) {
echo "<div class='letter-group'>\n";
echo "\t<div class='letter-cell'>$letter</div>\n";
start_new_row($letter);
}
function end_prev_row() {
echo "\t</div><!-- End row-cells -->\n";
}
function start_new_row() {
global $in_this_row;
$in_this_row = 0;
echo "\t<div class='row-cells'>\n";
}
?>

display items in grid?

i'm trying to display my portfolio items in a gird, but can't quite figure it out. ideally, i'd like the thumbnails to display 3 or 4 across(with the rest forming a second and/or third line) and once the thumbnails are clicked on, i'd like it to go to my normal post page.
css-
/* Portfolio */
#content {
width: 603px;
}
#portfolio-item {
display: inline;
float: left;
margin: 0 0 0 60px;
width: 280px;
}
#portfolio-item h1 {
font-size: 16px;
margin: 20px 0 5px 0;
}
#portfolio-item img {
height: 50%;
width: 50%;
}
portfolio.php:
<?php
/*
Template Name: Portfolio
*/
?>
<?php get_header(); ?>
<div id="portfolio">
<?php
$loop = new WP_Query(array('post_type' => 'portfolio', 'posts_per_page' => 10));
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
$custom = get_post_custom($post->ID);
$screenshot_url = $custom["screenshot_url"][0];
$website_url = $custom["website_url"][0];
?>
<div id="portfolio-item">
<?php the_post_thumbnail(); ?>
<?php the_content(); ?>
</div>
<?php endwhile; ?>
</div><!-- #content -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
functions.php:
<?php // sidebar functions
if(function_exists('register_sidebar'))
{
register_sidebar();
}
// portfolio functions
add_action('init', 'create_portfolio');
function create_portfolio() {
$portfolio_args = array(
'label' => __('Portfolio'),
'singular_label' => __('Portfolio'),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => true,
'supports' => array('title', 'editor', 'thumbnail')
);
register_post_type('portfolio',$portfolio_args);
}
// custom input- portfolio backend
add_action("admin_init", "add_portfolio");
add_action('save_post', 'update_website_url');
function add_portfolio(){
add_meta_box("portfolio_details", "Portfolio Options", "portfolio_options", "portfolio", "normal", "low");
}
function portfolio_options(){
global $post;
$custom = get_post_custom($post->ID);
$website_url = $custom["website_url"][0];
}
function update_website_url(){
global $post;
update_post_meta($post->ID, "website_url", $_POST["website_url"]);
}
// detail columns- portfolio backend
add_filter("manage_edit-portfolio_columns", "portfolio_edit_columns");
add_action("manage_posts_custom_column", "portfolio_columns_display");
function portfolio_edit_columns($portfolio_columns){
$portfolio_columns = array(
"cb" => "<input type=\"checkbox\" />",
"title" => "Project Title",
"description" => "Description",
);
return $portfolio_columns;
}
function portfolio_columns_display($portfolio_columns){
switch ($portfolio_columns)
{
case "description":
the_excerpt();
break;
}
}
// add thumbnail support
add_theme_support('post-thumbnails');
// disable autoformat with raw
function my_formatter($content) {
$new_content = '';
$pattern_full = '{(\[raw\].*?\[/raw\])}is';
$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($pieces as $piece) {
if (preg_match($pattern_contents, $piece, $matches)) {
$new_content .= $matches[1];
} else {
$new_content .= wptexturize(wpautop($piece));
}
}
return $new_content;
}
remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');
add_filter('the_content', 'my_formatter', 99);
?>
http://www.cssbakery.com/2010/07/image-grid-using-css-floats_6950.html
This should be what you're looking for.
You can hardcode it was well with PHP if you'd like using a table if you can't get that CSS working, but that's not good coding technically.

Resources