Home Template Loop customization - should fetch content based on post template - php

In the theme there are two files:
single.php
f-template.php → For default post type. It has different designs.
Home.php will fetch first 10 posts, and they can be among any of the above templates.
But, what is needed is when the content on home.php is coming from f-template.php
then these two things should be implemented on home.php
function folder_paragrapgh($content){
return preg_replace('/<p([^>]+)?>/', '<p class="para para2">', $content);
}
add_filter('the_content', 'folder_paragrapgh');
and
<script>
(function($) {
// do all your $ based jquery in here.
$(function() {
$('p.class2').prepend('<img src="http:/sample.com/img/folder.svg" width="50" height="25" alt="">');
});
})(jQuery);
</script>
I tried this:
if( is_page_template( 'f-template.php' ) ) {
function folder_paragrapgh($content){
return preg_replace('/<p([^>]+)?>/', '<p class="para para2">', $content);
}
add_filter('the_content', 'folder_paragrapgh');
}
the_content();
}
But this didn't work. actually it is flawed because the template that we are dealing is home.php.
So do we have any solution to achive what we wanted to achieve?

Correct me if I'm wrong but it sounds like you want to display a loop with posts where some posts have a different design depending on the Page Template you have selected for it.
You can check which template is being used with the get_page_template_slug() function. Use it inside the loop along with the ID of the post.
// checks if there are any posts that match the query
if (have_posts()) :
// If there are posts matching the query then start the loop
while ( have_posts() ) : the_post();
// Assign postId from within the loop
$postId = the_ID();
if( get_page_template_slug($postId) === 'f-template' ) {
// Display what you want to see when f-template is selected.
} else {
// Display what you want to see by default if no condition is met.
}
// Stop the loop when all posts are displayed
endwhile;
// If no posts were found
else :
echo '<p>Sorry no posts matched your criteria.</p>';
endif;
The is_page_template() function won't work because it will check what the page template for the current page in the Main Query is.
It all depends on your use case but personally I would have added an extra field using Advanced Custom Fields for this effect.
Good luck!

Related

How to run Wordpress Query by ACF field using Select on front-end

Basically what I'm trying to do is create filters on front end, so that users can filter all posts by specific ACF field.
There's a cattery website and the owner will need to add new litters, when new generations of kittens arrive. I've created option page for this new field group and created a repeater field with text, so that I can add new rows with names of the litters, I want to filter by later.
I've included basic loop for repeater field:
<select name="litter" id="litter">
<?php
if( have_rows('cat-litters', 'option') ):
while ( have_rows('cat-litters', 'option') ) : the_row(); ?>
<option value="<?php the_sub_field('new-litter', 'option'); ?>"><?php the_sub_field('new-litter', 'option'); ?></option>
<?php endwhile;
else :
endif;
?>
</select>
And it is working for now:
I will be adding a field to cats' posts named cat-litter, so that I can find specific posts with a litter "02" for example.
But now I'm stuck with using this select from front-end to run a query to display fitting posts.
I'm working in index.php of twentytwentyone child-theme btw.
It doesn't matter if it will need to reload page or not (however if the ajax way won't be complicated I would very much appreciate that) but I have to point out that it needs to work with pagination and I already have it set up with pre_get_posts to display 9 posts per page (3x3 grid).
Taken and modified from the Dynamic $_GET parameters section of this page per the ACF documentation: https://www.advancedcustomfields.com/resources/query-posts-custom-fields/
function my_pre_get_posts( $query ) {
// do not modify queries in the admin
if( is_admin() ) {
return $query;
}
// only modify queries for 'cat' post type
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'cat' ) {
// allow the url to alter the query
if( isset($_GET['cat-litter']) ) {
$query->set('meta_key', 'cat-litter');
$query->set('meta_value', $_GET['cat-litter']);
}
}
// return
return $query;
}
add_action('pre_get_posts', 'my_pre_get_posts');
Then on the front end for reloading the page with the 'cat-litter' from the dropdown could be done with jQuery:
<script>
$('select#litter').on('change', function() {
window.location.href = "www.website.com/cats?cat-litter=" + $(this).val();
});
</script>

How do you check the category of the next/previous post?

I'm working on a wordpress site with several categories, where each of those categories have posts. Example: I have "Work" and "Careers" as two categories.
When you click on a "Work" post, at the top of the page there is a "Previous / Next" button to display the next or previous post with the category "Work". Right now, the code is set up like this:
<div class="campaign__previous l-campaign__previous">
<?php previous_post_link('%link','Previous Campaign', TRUE); ?>
</div>
<span>/</span>
<div class="campaign__next l-campaign__next">
<?php next_post_link('%link','Next Campaign', TRUE); ?>
</div>
The wordpress function next_post_link('%link','LINK TEXT', TRUE) automatically doesn't display the link if there are no more posts in that category. That's great, but I also want to not display the
<span>/</span>
if there are no more posts in that category. How do I check this myself? I have tried:
if( next_post_link('%link','Next Campaign', TRUE) ) {
echo '<span>/</span>';
}
This did not work. Any ideas?
For WordPress functions that print something to the screen automatically, there is usually a version with the prefix get_ that will simply return the value. I don't have the ability to test this now but I assume the following might work or at least get you close:
if( get_next_post_link('%link','Next Campaign', TRUE) == "" )
// No More
else
// More to Come
Now there definitely seems like there is a better way to do this but this was just the first thing I thought of when I read your code.
https://developer.wordpress.org/reference/functions/get_next_post_link/

How to create different post layout for different categories and subcategories in wordpress

I've modified the single.php file in order to change layout for each category. In single.php I have this code
<?php
$post = $wp_query->post;
if ( in_category( '26') || get_term_children('26') {
include(TEMPLATEPATH . '/single-ric.php');
}
elseif ( in_category( '36') || get_term_children('36') {
include(TEMPLATEPATH . '/single-parl.php');
}
else {
include(TEMPLATEPATH . '/single-all.php');
}
?>
Is there something wrong in this code?
Each post article is shown with single-ric.php layout
Your question address few issues. First, as Pieter stated, you should use get_template_part instead of TEMPLATEPATH as it is deprecated.
What you need to do is to rename your templates to something like singlepost-ric.php, singlepost-parl.php and singlepost.php (instead of singlepost-all.php - that will be your fallback), this to prevent any fallback loop conflict - you need to place them at the same level as single.php to make this work. Then, use get_template_part in this way:
get_template_part('singlepost', 'ric');
If this doesn't work, use this to get the possible error messages:
assert("locate_template( array('singlepost-ric.php', 'singlepost.php'), false, false )");
The other issue is, and why your first condition is always true, is that you don't use right get_term_children. This function is used to get all the childrens of a term in a single array. If it don't find any, it will return an empty array, not false. This is why this (in_category( '26') || get_term_children('26')) is always true. By the way, you're missing a closing parenthesis in all your conditions.
I assume that what you want to do, is to know if the current post is in the category 26. Just remove the get_term_children part - it address something else. You probably added this because a category is a taxonomy, which would be valid then, but in_category is enough.
Last thing, you don't need this:
$post = $wp_query->post;
It is redundant. As you're within a template, the global var $post already contains the post you query.

Remove everything from output except between <p> tags

I have a Wordpress site that outputs content from individual blog posts with the_content()
Blog posts all consist of two things, a small gallery and some text:
<div class="gallery"><img></img>Blah Blah</div>
<p>Text</p>
<p>Text</p>
I'd like to split the gallery and the text and output the gallery in a div on the left and the text in a div on the right like this:
<div id="left">GALLERY CONTENT</div>
<div id="right">TEXT CONNTENT</div>
I have tried to do this with strip_tags(the_content(), '<p>') but this does not - it continues to output everything including the gallery.
What is the correct way to do this?
It is not really clear to me what you really want to do , and on to of it , you included some (very little ) source code from output, but to get a real shot at answering you need to include the relative code from the template file.
( And +1 for understanding alone that you should NOT TOUCH YOUR CORE FILES )
Anyhow, I suspect that you only want to disable the auto P generated by wordrpess , so try
remove_filter('the_content', 'wpautop');
(add to functions.php in theme.)
alternatively , you could use
add_filter('use_default_gallery_style', '__return_false');
Which will just "reset" the gallery styling .
or even filter your own gallery styles , which allows you to target them better.
add_filter( 'gallery_style', 'my_own_gallery_style', 99 );
function my_own_gallery_style() {
return "<div class='gallery'>"; // put your own
}
If it does not produce the right output for you, please include more specifics and / or more code .
There are of course more advanced ways to handle this , but Without more info it is difficult to target .
For example you can create your own gallery style by removing the original shortcode function, and then adding your own, but those are a bit more advanced techniques.
// deactivate WordPress function
remove_shortcode('gallery', 'gallery_shortcode');
// activate your own own function
add_shortcode('gallery', 'my_own_gallery_shortcode');
// the own renamed function
function my_own_gallery_shortcode($attr) {
...
}
Now on the other hand , If you want to "catch" some parts of 'the_content' and display it in a loop in a different manner , you can always use a different technique, like described HERE on another answer .
You are using the_content which displays the content instead of returning it.
Change your code to
strip_tags(get_the_content(), '<p>')
I had this exact same problem a while ago. Here's what I did (in single.php, which is where I had the problem):
if ( get_post_format() == 'gallery' ) :
$content = get_the_content();
$gallery_regex = '/\[gallery.*]/s'; //identify the [gallery] tags within the content
//get gallery code
$gallery = preg_match($gallery_regex, $content, $matches);
$gallery = $matches[0];
//remove gallery from content
add_filter('the_content', function($content){
$gallery_regex = '/\[gallery.*]\s*/s';
return preg_replace($gallery_regex, ' ', $content);
});
endif;
Basically, I used regex to remove the gallery tags from the content.
$gallery still contains the shortcode. We can't just randomly display it, or it'll actually show the shortcode. We need to execute it, which will show the output:
if ( get_post_format() == 'gallery' ) {
echo '<div id="left">'. do_shortcode($gallery) .'</div>';
}
Your content no longer contains the gallery, so you can do this:
<div id="right"><?php the_content(); ?></div>

Wordpress: include content of one page in another

How do I include the page content of one or more page in another page?
ex. I have pageA, pageB and pageC and I want to include the contents of these pages in pageX
is there a wordpress function that loads the post of a specified page/post?
like show_post("pageA")??
There is not a show_post() function per se in WordPress core but it is extremely easy to write:
function show_post($path) {
$post = get_page_by_path($path);
$content = apply_filters('the_content', $post->post_content);
echo $content;
}
Note that this would be called with the page's path, i.e.:
<?php show_post('about'); // Shows the content of the "About" page. ?>
<?php show_post('products/widget1'); // Shows content of the "Products > Widget" page. ?>
Of course I probably wouldn't name a function as generically as show_post() in case WordPress core adds a same-named function in the future. Your choice though.
Also, and no slight meant to #kevtrout because I know he is very good, consider posting your WordPress questions on StackOverflow's sister site WordPress Answers in the future. There's a much higher percentage of WordPress enthusiasts answering questions over there.
I found this answer posted on the Wordpress forums. You add a little code to functions.php and then just use a shortcode whenever you like.
function get_post_page_content( $atts ) {
extract( shortcode_atts( array(
'id' => null,
'title' => false,
), $atts ) );
$the_query = new WP_Query( 'page_id='.$id );
while ( $the_query->have_posts() ) {
$the_query->the_post();
if($title == true){
the_title();
}
the_content();
}
wp_reset_postdata();
}
add_shortcode( 'my_content', 'get_post_page_content' );
For the shortcode,
[my_content id="Enter your page id number" title=Set this to true if you want to show title /]
Pages are just posts, with a post_type of 'page' in the database. You can show the content of multiple pages on another page by writing a post query in your pageX template that gets the posts you specify and output them in a Loop.
There are three ways to get post content from the database:
get_posts
query_posts
WP_Query
These links all point to the WordPress Codex. Get_posts and query_posts have an argument available, 'page_id', where you can specify the id of the page you'd like to retrieve and display.
You could install a Plugin "Improved Include Page". Once installed, you create page X and enter:
[include-page id="123"]
[include-page id="124"]
[include-page id="125"]
where these are the ID's of pages A, B and C respectively
<?php query_posts('p=43');
global $more;
//set $more to 0 in order to only get the first part of the post
$more = 0;
// the Loop
while (have_posts()) : the_post();
// the content of the post ?>
the_title();
the_content();
endwhile; ?>
This is obviously a portion of the post, I got the detail from the wordpress codex.
Interesting... I looked around for how to embed Wordpress content elsewhere (as in, on another website), and found some things...
www . shooflydesign.org/buzz/past/embedding_wordpress . html
Shows how to embed Wordpress content in another site with a php script; maybe just use the same thing to embed Wordpress into itself?
www . corvidworks . com/articles/wordpress-content-on-other-pages
Similar concept; embed Wordpress on another page; just try to use that tool in a new WP post
feeds themselves
My searching pulled up some suggestions to just use a feed to your own blog to embed into a post. There's nothing preventing that. You might want it automated and so restructuring the feed to look right might be problematic, but it's worth a shot depending on what you want to do.
Hope those are quasi-helpful. While they all are solutions for getting your WP content on some place other than WP... they might work for your given question and allow you to display A, B, and C on X.
There is a Wordpress function to display the content of a particular page inside another using query_posts() it is:
<?php query_posts("posts_per_page=1&post_type=page&post_id=134"); the_post(); ?>
You set the number of pages to be displayed to 1, post type is page instead of post and the page id
Kit Johnson's wordpress forum solution with creating a shortcode works, but adds the inserted page in the top of the new page, not where the shortcode was added. Close though, and may work for other people.
from the wordpress post, I pieced together this which inserts the page where the shortcode is put:
function get_post_page_content( $atts ) {
extract( shortcode_atts( array(
'id' => null,
'title' => false,
), $atts ) );
$output = "";
$the_query = new WP_Query( 'page_id='.$id );
while ( $the_query->have_posts() ) {
$the_query->the_post();
if($title == true){
$output .= get_the_title();
}
$output .= get_the_content();
}
wp_reset_postdata();
return $output;
}
Then, the shortcode bit works as expected. If you don't want the title, title=false does not work, you need to leave title off entirely.

Categories