Wordpress Permalink to specific blog posts, not current URL - php

I have a loop on my homepage showing 3 recent blog posts, this is being included in from the footer. If I go elsewhere on the site though such as a different blog post, the 'the_permalink' is instead of grabbing the featured 3 blog post links, it's grabbing the link from the page your currently on.
These 3 blog posts will change as new ones are added so I cannot define that the link be only a specific blog post(s).
Here is the code showing the first blog post. Found within footer.php and therefore shows on each page.
<div id="news-container-1">
<?php
// Create a variable to hold our custom Loop results
$excludes = array('4135');
$frontpageposts = get_posts( array(
'numberposts' => 1, // only the 3 latest posts
'post__not_in' => $excludes
) );
// Create output only if we have results
// Customize to suit your HTML markup
if ( $frontpageposts ) {
foreach ( $frontpageposts as $fppost ) {
// setup postdata, so we can use template tags
setup_postdata($fppost);
?>
<div <?php post_class(); ?>>
<h4><?php //the_title(); ?>Latest News #1</h4>
<div class="post-entry">
<?php
$content = $post->post_content;
$searchimages = '~<img [^>]* />~';
/*Run preg_match_all to grab all the images and save the results in $pics*/
preg_match_all( $searchimages, $content, $pics );
// Check to see if we have at least 1 image
$iNumberOfPics = count($pics[0]);
if ( $iNumberOfPics > 0 ) { ?>
<!-- GRAB THE IMAGE AND USE WHATEVER HTML YOU LIKE -->
<img src="<?php echo catch_that_image() ?>" alt="<?php the_title(); ?>" /></a>
<?php }
?>
<?php //the_excerpt(); ?>
</div>
</div>
<?php }
}
?>
</div>

the_permalink() doesn't have any parameters so remove the '1'.
You need to change the way you're setting up the posts. setup_postdata() is currently being used incorrectly.
if ( $frontpageposts ) {
global $post;
foreach ( $frontpageposts as $post ) {
// setup postdata, so we can use template tags
setup_postdata( $post );
Then at the end of your foreach loop you need to reset the post object.
Change this:
<?php }
}
To this:
<?php }
wp_reset_postdata();
}

Related

Get ACF field data within foreach loop - wordpress

I have a custom image field for all pages with a specific page template (using ACF plugin).
I'm querying for these pages like so:
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'meta_value' => 'services-page.php'
));
Then I'm displaying pages with a foreach loop:
if( $posts ): ?>
<?php foreach( $posts as $post ): setup_postdata( $post );?>
//content goes here
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
Now I want to access the custom field to display inside the loop. But, below doesn't work. I'm guessing because ACF fields don't get appended to the post object.
//Does not work
$image = $post -> services_block_image
ACF has the get_field() function, but what can I do to get the field for each of the posts from my original query? Found ACF docs to be rather confusing on this (goes without saying I'm a bit new to PHP).
Within loop use get_field function to get the image.
check below code for your reference.
$image = get_field('services_block_image'); // get the image
if( !empty($image) ): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<?php endif; ?>

WP Custom Tabs System- Multiple Loops for Multiple Custom Post Types

I'm building a Wordpress site right now and I'm trying to create a tab structure on a single page where I can create a sort of sub-menu and display 4 different custom-post-type loops, depending on what menu item is selected. I've been able to get the nav-items block consistent with a foreach loop, and the content blocks are switching correctly, but right now, each content div is displaying all the posts of every custom-post-type that I have.
I've experimented with switch statements and if statements as well as the is_singular conditional tag, but nothing is working quite right thus far
I've put comments in the code to delineate for myself what each section is doing, thought they might help you get into my brain space.
<ul class="tab" role="tablist">
<?php
//All public posts that are not built into Wordpress
$argsnav = array(
'public' => true,
'_builtin' => false,
);
$output = 'objects'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
//Get the Post Types of each post as an object
$post_types = get_post_types( $argsnav, $output, $operator );
//Remove Product from Array
unset( $post_types ['product'] );
//Iterate through each post type
foreach ($post_types as $post_type) {
//And print out a list item with the corresponding ID and text
echo '<li>
<a href="#' . $post_type->name . '" role="tab" data-toggle="tab">
'. $post_type->label .'
</a>
</li>';
}
echo '</ul>';
?>
//New section for post content/ This is the buggy portion
<div class="tab-content">
<?php
//Iterate through each post type
foreach($post_types as &$post_type) { ?>
<!--Create div with corresponding id-->
<div class="tab-pane" id="<?php echo "$post_type->name" ?>">
<!--Create new query for all posts of each type-->
<?php $loop = new WP_Query(
array(
'post_type' => array('standup', 'novels', 'short_stories', 'music'),
));
//Loop through and display each post's title
if ( $loop->have_posts()) :
while ( $loop->have_posts() ) :
$loop->the_post(); ?>
<h2><?php the_title(); ?></h2>
<!--Stop the loop-->
<?php endwhile; ?>
<?php endif; ?>
</div>
<?php } wp_reset_postdata(); ?>
</div>
I think I know what needs to be done, but HOW is where I'm stuck. Any help is very much appreciated!
As I feel, you do not need to set all post_type in wp_query, please try this
<!--Create new query for all posts of each type-->
<?php $loop = new WP_Query(
array(
'post_type' => $post_type->name,
));
//Loop through and display each post's title

Getting related articles in WordPress not working

I am trying to display all the posts with the same category in WordPress however its not displaying correctly and instead is just showing everything.
Here is the php code:
<?php
$related = get_posts( array(
'category_in' => wp_get_post_categories($post->ID),
'numberposts' => 3,
'post_not_in' => array($post->ID) ) );
if( $related ) foreach( $related as $post ) {
setup_postdata($post); ?>
<div class="post">
<a href="<?php the_permalink(); ?>">
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
<h3><?php the_title();?></h3>
</a>
</div>
<?php }
wp_reset_postdata();
?>
Its taken from here: https://wordpress.stackexchange.com/questions/41272/how-to-show-related-posts-by-category
And if it helps here is the link to the website in question where the code isnt working:http://u1f8aki.nixweb23.dandomain.dk/cat-4-post-test/
The code in question is further down the page under the red text. You can see the category at the top in the breadcrumbs.
There are quite errors in your code, and I'm sure atleast one of them are the culprit in giving you the wrong result.
I've refactored your code with some comments explaining what and why has been changed:
<?php
// For readability, save our categories in a variable for later use.
// $post->ID has been replaced with get_the_ID(), $post might not be accessible depending if you're exposing $post as a global or not.
$categories = wp_get_post_categories(get_the_ID());
/*
Instead of using get_posts(), use the recommended Wordpress loop in the form of WP_Query().
We start by defining our arguments for the loop
*/
$args = array(
'category_in' => $categories, // here we use variable for readability
'posts_per_page' => 3, //numberposts and posts_per_page has the same function, but posts_per_page is the more common of the two (IMO)
'post__not_in' => array(get_the_ID()) // you were missing a '_', ie post_not_in instead of post__not_in
);
// Start the loop
$query = new WP_Query($args);
if($query->have_posts()): while($query->have_posts()): $query->the_post();
// No need to setup or reset postdata when using this method, it does it for you!
?>
<div class="post">
<a href="<?php the_permalink(); ?>">
<?php
if( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
<?php
// the_title() actually takes opening tag and closing tags as arguments in its function. So add the <h3> code like this.
the_title('<h3>', '</h3>');
?>
</a>
</div>
<?php endwhile; endif; ?>
Long story short, your code prolly isn't working because of the miss-named arguments. If you don't feel like replacing your code with my example, just change your arguments from numberposts to posts_per_page, and post_not_in to post__not_in.
If it still isn't working, check what wp_get_post_categories(get_the_ID()) is returning for each post, and make sure all posts aren't sharing some category you missed.
Edit: numberposts is actually a valid argument, changed my answer to reflect this.

Only showing the first sentence of a WordPress post on the front page as a "highlighted post" section

I'm currently working on my first WordPress theme and I want to create a "Highlighted Post" section on my index.php. There are a lot of scripts for this but all seem to apply a permanent filter over the entire index.php. That is problematic since i want to show the whole posts on my index.php below. Is there a way to apply this special filter only for this section and not for the whole index.php?
If you could give us more info what determines this "Highlighted" posts we might be able to be more specific in solving this.
But in the mean time I'll guess it's two latest posts which means you could have two queries in the index.php
First one would be for "Highlighted" ones:
<?php
$args = array( 'numberposts' => 2 );
$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post);
?>
<h2 class="news"><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<?php endforeach; ?>
This will give you excerpt of your post in this query.
What you could do then is limit excerpt to whatever length you'd like and add read more link if you want :)
function newExcerpt($more) {
global $post;
return '... Read more';
}
add_filter('excerpt_more', 'newExcerptReadMore');
function customExcerptLength( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'customExcerptLength', 999 );
And for other posts you could do another query but not using first two posts like this:
$count = 0;
$lastposts = get_posts();
foreach($lastposts as $post) : setup_postdata($post);
if($count > 1)
?>
<h2 class="news"><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
$counter++;
<?php endforeach; ?>
This will just loop through the posts and skip first two posts.
If you have some other term or category or something else that determine Highlighted posts then you can use that in and pass it as an argument to get_posts($args).

ACF: Display Fields in a template based on Cpt ui

I have created a custom post type based on CPT Ui I am tryin to display the items of that in a template ideally what I want to be able to do is
www.siteurl.com/profile/profilename
Hence why I have created a template page with the following code.
But I dont no how I would get profilename into my query posts and then display the relivent data this is what I have tired so far to get id and permalink to display but to no avail.
I really want to be able to do it like how the documentation states. Ideally i would suspect my best approach would be to check if user has created a profile in the front end if not direct them to do so?.
Display a field
<p><?php the_field('field_name'); ?></p>
http://www.advancedcustomfields.com/resources/code-examples/
<?php
/**
* Template Name: Profile Page
*/
get_header(); ?>
<?php get_template_part( 'page', 'title' ); ?>
<div class="width-container">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php endwhile; // end of the loop. ?>
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'profiles',
'meta_key' => 'profilename',
'meta_value' => 'david'
));
if($posts)
{
echo '<ul>';
foreach($posts as $post)
{
echo '<li>' . get_the_title($post->ID) . '</li>';
}
echo '</ul>';
}
?>
<?php get_sidebar(); ?>
</div><!-- close .width-container -->
<?php get_footer(); ?>
If anyone has done anything simlar maybe I should be using current user but again i dont no how to link that up to acf as I am new to that plugin
Perhaps you could try another approach and build a custom query with WP_Query instead. The example bellow use the WP_Query object rather than the get_posts function, however the arguments and logic remain the same.
This implies we will find all posts that have a post_type of profiles where the ’custom field’ profilename is equal to david. The custom field ‘profilename’ in this case could be a text field, a radio button or a select field (something that saves a single text value).
<?php
/**
* Template Name: Profile Page
*/
get_header();
$user = get_post_meta($post->ID, 'profilename', true); // saving the field value in a $variable can help to build a more dynamic WP_Query...
?>
<?php get_template_part( 'page', 'title' ); ?>
<div class="width-container">
<h1>__('Listing Posts by:', 'text_domain');</h1>
<?php echo '<p class="text-center">' . esc_html( $user ) . '</p>'?>;
<?php
// args
$args = array(
'numberposts' => -1,
'post_type' => 'profiles',
'meta_key' => 'profilename',
'meta_value' => $user // retrieve the actual profilename field value
);
// query
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
<ul>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
<?php get_sidebar(); ?>
</div><!-- close .width-container -->
<?php get_footer(); ?>
The code above is an example of how to query ("get and display") posts in WP using WP_Query object within a template based on custom field called ‘profilename’ which has a value of ‘david’ or whatever data is saved inside the field as per your example.
Perhaps you want to display the relevant data (values) of the custom fields you've created for the WP default user profile page, and if this is the case, you should follow another approach and instead of query posts you simply output the fields a user might fill on their profile. In order to that you could Get values from a user.
This example will display the field 'profilename' value from a user with an ID of 1.
<?php the_field('field_name', 'user_1'); ?>
Within your loop you could use $user_ID = get_current_user_id(); to retrieve the user_id as follows:
<?php
/**
* Template Name: Profile Page
*/
get_header();
$user = get_post_meta($post->ID, 'profilename', true); // saving the field value in a $variable can help to build a more dynamic WP_Query...
$user_ID = get_current_user_id();
?>
<?php get_template_part( 'page', 'title' ); ?>
<div class="width-container">
<h5>__('Listing Posts by:', 'text_domain');</h5>
<h1><?php the_field('profilename', '$user_ID'); ?>;</h1> // this will retrieve the data/value saved in the 'profilename' field for the current user
...
Check ACF's Query Posts by Custom Fields documentation for other ways to retrieve an array of post objects from the database using native WP functions.

Categories