My foreach is only applying to the first instance [duplicate] - php

This question already has answers here:
How can I apply a jQuery function to all elements with the same ID?
(4 answers)
Closed 5 years ago.
I have a wordpress site where my index page will display the post title, thumbnail, and list all available post categories. Each instance of a post will also display all available post categories. For each category the post has, the category name should be highlighted with a light blue background color. Currently the background color feature is working for only the first post and not the other three.
My code below is intended to push each of the post's categories into an array and search the array for the given category (the code below searches for just one of the categories for brevity's sake here). If the category is found, a jQuery script should execute highlighting the category name but as I say above, it's only functioning for the first post.
Can anyone see what I'm doing wrong? Thanks in advance.
<section class="blog-index">
<?php
$args = array('showposts' => 3);
$recent = new WP_Query( $args );
if( $recent->have_posts() ):
echo '<div class="blog-index-list">';
while ( $recent->have_posts()) :
$recent->the_post();
$categories = get_the_category();
$cats = array();
foreach($categories as $category) {
$cats[] = $category->name;
}
if(in_array("Academia", $cats)) {
echo "<script type='text/javascript'>
jQuery('#A').addClass('active');
jQuery('#A').css({'background-color': #009edb', 'color': '#ffffff'});
</script>";
}
echo '<article>
<h2><hr class="orange-line above-left"> <a href="'.get_the_permalink().'">
<span class="dark-blue">' .get_field('dark_blue_hero'). '</span><br/>
<span class="light-blue">' .get_field('light_blue_hero') . '</span></a>
</h2>
<ul class="all-categories">
<li id="G">G</li>
<li id="A">A</li>
<li id="I">I</li>
<li id="N">N</li>
</ul>
<img src="'.get_the_post_thumbnail().'' .
'<div class="blog-index-button et_pb_button_module_wrapper et_pb_module et_pb_button_alignment_center">
<a class="et_pb_button et_pb_button_3 et_pb_module et_pb_bg_layout_light" href="' . get_the_permalink() . '">READ POST</a>
</div>
</article>';
endwhile;
echo '</div>';
endif;
wp_reset_query();
?>

IDs should be unique (as Barmar said) but it is still possible to have multiple elements with the same ID. And it is possible to select them with jQuery. That is why I'll also explain how to do it with classes.
When you use the jQuery ID selector (jQuery("#id")) it selects the first element with the given ID id.
To select all elements with ID id you can select them by their attribute(s):
jQuery("li[id=id]")
Since IDs should be unique it is better to use classes. Using the jQuery class selector jQuery(".class") you can select all the elements with the class class. You should change your li elements to have classes instead of IDs and select those classes with jQuery.

Related

have_posts() while loop ignores any HTML being returned

So basically I'm creating a small function to get the most recent posts with a certain category from WordPress, and just link them in a Test page. The function itself works, grabbed it from this stackexchange thread. My while loop set up currently ignores all the HTML/CSS i try to return.
Removing the_post() ignores $args and lists all the posts from all the categories instead of just the one i listed, but still ignores the HTML.
Removing wp_reset_postdata() does nothing as much as I can see, doesn't resolve my issue.
Adding <br> or clearfix divs does not resolve the issue.
Having the return inside the while loop only posts the last recent post as it closes the loop once returned.
Tried using echo instead of return, same result.
function link_recent_posts(){
$text = "";
$args = array('posts_per_page' => 2,
'cat' => '144',);
$q = new WP_Query($args);
if($q->have_posts() ){
while( $q->have_posts() ){
$q->the_post();
$text .= "<a href='".the_permalink()."'>".the_title()."</a><br>";
}
wp_reset_postdata();
}
return $text;
}
add_shortcode('TestRecentPosts', 'link_recent_posts');
The expected result should be
<a href='LINK1'> TITLE TITLE TITLE </a><br>
<a href='LINK2'> TITLE TITLE TITLE </a><br>
The result I get is :
<div class="wordpress-content-section">
<div class="clearfix"></div>
LINK 1
TITLE 1
LINK 2
TITLE 2
<br>
<br>
</div>
Imagine that there's 0 spaces between the links and titles.
Issue Resolved
Removed the return
Instead of incrementing the $text variable, i added an echo for the line.
Instead of using the_permalink() and the_title(), I used get_the_permalink() and get_the_title().
Use get_the_permalink() and get_the_title() instead.
the_permalink() and the_title() echoes the results directly.
SEE
https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/post-template.php#L0
https://developer.wordpress.org/reference/functions/the_permalink/

show correct category name and fix post title permalink wordpress

I use this code to show different posts in different divs.
I have 2 problems:
I can't show the correct category name to current post.
The same category name is applied to 2 post when I use:
get_category_link($recent['ID'])
Clicking on the post title redirect me to home page instead post's page!
<div class="modulex">
<?php
$args = array('numberposts' => '1', 'post_status' => 'publish', 'offset' => '2');
$recent_posts = wp_get_recent_posts($args);
foreach ($recent_posts as $recent) {?>
<div><?php echo get_the_post_thumbnail($recent['ID'],'small', array('class'=>'img-fluid')); ?></div>
<div class="spanlike"><h6><?php echo $recent["post_title"] ?></h6></div>
<?php } ?>
</div><?php
wp_reset_query();
?>
The problem with this is that get_category_link requires a category ID as argument, not post ID. To get around this, you'll have to perform several steps:
retrieve a list of categories for your post
decide which category to use from the list (assuming you only have one category per post, just use the first/only one)
get the link for this category
I would suggest using a custom function for this. Example below.
Here I think your problem is that get_permalink returns rather than echos. You could use the permalink instead:
<div class="spanlike"><h6><?php echo $recent["post_title"] ?></h6></div>
Example function for retrieving category link from post ID:
function get_cat_link_from_postID($postID) {
$categories = get_the_category($postID);
$catID = $categories[0]->term_id;
return get_category_link($catID);
}

Isotope - show latest post within each category

How it works right now:
It shows the latest 6 projects as default
When pressing the specific lists it shows the latest post within that category that are the latest 6 projects. E.g: It shows the 4 latest within Foto because 4 of the 6 are categories as Foto. This mean that if the 6 latest projects are in the category Foto, none of the posts within the other categories would show. Please see screenshow below if you don't understand.
How it should work:
Show the latest 6 projects as default (this works)
When press one category it should show the latest 6 posts within that category
See page here
Note: If you are using Chrome with Windows 10 the hover effect has for some reason stopped working. The bug has been reported to Chrome and Windows
<ul id="filters" class="whitetext whitelink myeluft">
<li class="smoothtrans">Alle</li>
<li class="smoothtrans">Foto</li>
<li class="smoothtrans">Video</li>
<li class="smoothtrans">Web</li>
</ul>
PHP
<?php
$args = array(
'post_type' => (array( 'foto', 'video', 'web' )),
'posts_per_page' => '6',
'post_taxonomy' => 'any',
);
$the_query = new WP_Query($args);
// Loop post_type
?>
<?php if ( $the_query->have_posts() ) : ?>
<div id="isotope-list">
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$termsArray = get_the_terms( $post->ID, "category"); //Get the terms for this particular item
$termsString = ""; //initialize the string that will contain the terms
foreach ( $termsArray as $term ) { // for each term
$termsString .= $term->slug.' '; //create a string that has all the slugs
}
?>
<div class="<?php echo $termsString; ?> item col-md-4">
<ul class="grid cs-style-3">
<li>
<figure>
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail('frontpage_thumb');
} ?>
<figcaption class="lefttext">
<h3><?php the_title(); ?></h3>
<span class="offgrey"><?php echo(types_render_field( "produkt", array( 'raw' => true) )); ?> / <?php echo(types_render_field( "produsert", array( 'raw' => true) )); ?></span>
Se prosjekt
</figcaption>
</figure>
</li>
</ul>
</div> <!-- end item -->
<?php endwhile; ?>
</div> <!-- end isotope-list -->
<script src="<?php bloginfo('stylesheet_directory'); ?>/js/toucheffects.js"></script>
<?php endif; ?>
JS
jQuery(function ($) {
var $container = $('#isotope-list'); //The ID for the list with all the blog posts
$container.isotope({ //Isotope options, 'item' matches the class in the PHP
itemSelector : '.item',
layoutMode : 'masonry'
});
//Add the class selected to the item that is clicked, and remove from the others
var $optionSets = $('#filters'),
$optionLinks = $optionSets.find('a');
$optionLinks.click(function(){
var $this = $(this);
// don't proceed if already selected
if ( $this.hasClass('selected') ) {
return false;
}
var $optionSet = $this.parents('#filters');
$optionSets.find('.selected').removeClass('selected');
$this.addClass('selected');
//When an item is clicked, sort the items.
var selector = $(this).attr('data-filter');
$container.isotope({ filter: selector });
return false;
});
});
My thoughs (updated 13/07/15)
I have looked more into it, and when disabling the 'posts_per_page' and just using the custom wp settings, the problem is the same. So I guess that the problem is that when pressing each category it does not refresh or get any other posts than first shown.
I therefore believe that the args must be set another place, or the js must be modified to get newest posts. But this is not my expertise, and therefore I ask you if you have any solution. I have searched on both search engines and SO for this question, but I couldn't find it. However, I see that similar pages have the same problem. With that I believe that solving this problem would help other users aswell.
Your current code ask to the database for 6 recent posts only. Isotope plugin then filter them on the frontend.
This means that it can't show more post apart from this 6. When you click on the tags (foto, video, web) isotope filter this 6 posts to show only the ones that have the selected category. It doesn't ask for any more posts, it only filter the posts you already have.
You can make your code ask for more posts when you click on the filter tags, but you will need to use AJAX.
Two Things I don't understand
Why their are two navigation/choice
2.First one work correct but second does not have any link or function it has link to just back to same using # hyper reference.
3.video and web have same thing did you put it knowingly if not check assigned category
one thing you can do is fetch all the posts at once and show only 6 using something like this
jQuery('#isotope-list').isotope({
filter: ':nth-child(-n+3)'
});
Filter will work only on available items on page.
When pressing one category it should show the latest 6 posts within that category if available, in your case (http://www.vekvemedia.no/) total item are 6 and 5 item belongs to "foto" category so when pressing "foto" category it will show 5 items.
Solution-1: if you have "All" option then you have to load all the available items in first load after that filter will work and show all the items of matching category.
Solution-2: By using ajax, fetch 6 records that match category(like "foto")

Excluding a Category Name (Not Posts) From A WordPress Template

I'm currently working with a template (Point from MyThemeShop) in WordPress that has been functioning fairly well for me. I've already made some customizations but am having one issue.
The theme pulls the most recent posts and displays them in a "Featured Posts" area at the top of the page. I wanted more control over the posts displayed here so I set up a category (Homepage Featured Posts) to better define which posts should show up there. Works well, however, under this area where the recent post feed is . . . the thumbnail previews pull and display the category name in alphabetical order. So, if I have a featured post categorized under "Review" also, the preview thumbnail currently says "Homepage Featured Post" instead of "Review". I would like to exclude "Homepage Featured Post" from showing up in these thumbnails (and one other category I've also defined, "Trending Articles").
In the Index Template the code that seems to pull the category names is this:
<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>" rel="nofollow" id="featured-thumbnail">
<?php echo '<div class="featured-thumbnail">'; the_post_thumbnail('featured',array('title' => '')); echo '</div>'; ?>
<div class="featured-cat"><?php $category = get_the_category(); echo $category[0]->cat_name;?></div>
<?php if (function_exists('wp_review_show_total')) wp_review_show_total(true, 'latestPost-review-wrapper'); ?>
</a>
I've tried an exclusion method that sort of worked . . . but ended up not pulling ANY categories instead, using this method on line 4:
<div class="featured-cat"><?php $category = get_the_category(); echo $category[0]->cat_name !--'Homepage Featured Post';?></div>
Do I need to use specific category ID's? I am unsure how to accomplish this. Any help is much appreciated.
<?php
foreach((get_the_category()) as $cat) {
if ( $cat->cat_name!=='Homepage Featured Post' || $cat->cat_name!=='Trending Articles' ) {
echo $cat->cat_name . ' ';
}
}
?>
Can you use above code.

Can I show a list of contacts within category, on the 'List all contact categories' page in Joomla?

So in a nutshell, you have two options for displaying Contacts in Joomla:
Show all Joomla Contact Categories.
Show all Joomla Contacts in a single Category.
I want to use the first option, but merge a list underneath each Category showing the list of contacts within that category, and a link to their profile.
The simplest way I thought of this was to edit a template override of the file com_contact/categories/default_items.php
I found a point where I want the list to appear, and then copied and pasted the code from the Category view (that generates the list of contacts).
<ul>
<?php // Add list of contacts for each category
foreach ($this->items as $i => $item) : ?>
<li>
<a href="<?php echo JRoute::_(ContactHelperRoute::getContactRoute($item->slug, $item->catid)); ?>">
<?php echo $item->name; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
But I am assuming I can't just copy and paste, as there needs to be an extra node added to $this->items.
At the moment, no list is being generated, just the <ul> outside the foreach loop.. but also interestingly, the <li> and the <a> IS being generated.. but linking to the current page I'm on (Probably because $item->slug is still being seen as the category).
So can anyone point me in the right direction as to how to reference the contacts within a category? All I'm after is the name and the slug/URL.
UPDATE:
I saw this in the same file (default_items.php) and although I realise it's referring to child categories... would this be a place to start for the actual contacts within the categories?
<?php if (count($item->getChildren()) > 0) :?>
<div class="collapse fade" id="category-<?php echo $item->id;?>">
<?php
$this->items[$item->id] = $item->getChildren();
$this->parent = $item;
$this->maxLevelcat--;
echo $this->loadTemplate('items');
$this->parent = $item->getParent();
$this->maxLevelcat++;
?>
</div>
<?php endif; ?>
BUMP - Does anyone have any experience with this? Or being able to call individual contacts when viewing a category? How are they linked?
For Category view in file default_children.php after tag <li... add code:
<?php
// Get Category Model data
$categoryModel = JModelLegacy::getInstance('Category', 'ContactModel', array('ignore_request' => true));
$categoryModel->setState('category.id', $child->id);
$categoryModel->setState('list.ordering', 'a.name');
$categoryModel->setState('list.direction', 'asc');
$categoryModel->setState('filter.published', 1);
$contacts = $categoryModel->getItems();
?>
For Custom Fields add this after previus code:
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
foreach($contacts as $contactItem) {
$currentContFields[] = FieldsHelper::getFields('com_contact.contact', $contactItem, true);
}

Categories