How to get the next $args when if:false? - php

I am new in programming... (The question absolutely about programming, but I use wordpress) I try to be very clear:
I have a subdomain based multisite network. If the users posts to their sites, I get a clone from the current post to my network home. This clone have a canonical url, what shows to the original post, and the post slug's also concur (the ID's dont.)
example: x user posted:
url: xusersite.network.com/4243345/this-is-slug-by-post-title
canonical: xusersite.network.com/4243345/this-is-slug-by-post-title
I get:
url: network.com/123677745/this-is-slug-by-post-title
canonical: xusersite.network.com/4243345/this-is-slug-by-post-title
Now I want get the clone post's ID, on the subsite, by the original post... so I have this code:
switch_to_blog( 1 );
$canonical = 'xusersite.network.com/4243345/this-is-slug-by-post-title';
$slug = 'this-is-slug-by-post-title'; // current slug
$args = array(
'name' => $slug,
'post_type' => 'post',
'post_status' => 'publish',
'numberposts' => 1
);
$my_posts = get_posts($args);
Thats ok, but the problem, if an another user posted with the same title for his blog, example: y user posted:
url: yusersite.network.com/72543/this-is-slug-by-post-title
canonical: yusersite.network.com/72543/this-is-slug-by-post-title
I get a post, with the same slug:
url: network.com/776536556733/this-is-slug-by-post-title
canonical: yusersite.network.com/72543/this-is-slug-by-post-title
So my php knowledge now here it is, I can do this:
if( $my_posts ) :
$cloneid = $my_posts[0]->ID;
$clonecanonical = wp_get_canonical_url( $cloneid );
if( $clonecanonical == $canonical ) :
$exit = 'true';
else :
$exit = 'false';
endif;
endif;
How can I get the next $my_posts, so $my_posts[1]->ID, if the $exit is false? How can I get the right $my_posts?

Not sure to have understood, but you should get the numeer of posts in my posts using count($my_posts) and then use a for or while to iterate through the full $my_posts.
something like this:
if( $my_posts ) :
$numPosts=count($my_posts)
//if $numPosts = 0 then $my_posts[0] does not exist
//but if you are here $numPosts must be > 0
if $numPosts > 0 {
for ( $i = 0; $i < $numPosts; $i++ ){
$cloneid = $my_posts[$i]->ID;
$clonecanonical = wp_get_canonical_url( $cloneid );
if( $clonecanonical == $canonical ) :
$exit = $my_posts[$i]->ID;
endif;
}
}
endif;

Related

Custom Fields not showing in custom post type post

I have a custom post type named "Designer" Each posts will be using different unique Advanced Custom Fields as each posts has unique templates.With the below code I am able to give rules for each posts in Designer post type and save but the custom fields are not displaying on post edit pages on backend.
Normally this code should ork but no idea what happend to the code
Please Help.
add_filter('acf/location/rule_types', 'acf_location_rules_types');
function acf_location_rules_types( $choices )
{
$choices['Custom Post types']['cpt_parent'] = 'Custom post type parent';
return $choices;
}
add_filter('acf/location/rule_values/cpt_parent', 'acf_location_rules_values_cpt_parent');
function acf_location_rules_values_cpt_parent( $choices )
{
$args = array(
'hierarchical' => true,
'_builtin' => false
);
$posttypes = get_post_types( $args );
if( $posttypes )
{
foreach( $posttypes as $posttype ):
if( $posttype != 'acf' ):
$args = array(
'post_type' => 'designer',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$customposts = get_posts( $args );
if ( $customposts ) {
foreach( $customposts as $custompost ){
$choices[ $custompost->ID] = $custompost->post_title;
}
}
endif;
endforeach;
}
return $choices;
}
//MATCH THE RULE
add_filter('acf/location/rule_match/cpt_parent', 'acf_location_rules_match_cpt_parent', 10, 3);
function acf_location_rules_match_cpt_parent( $match, $rule, $options )
{
global $post;
$selected_post = (int) $rule['value'];
// post parent
$post_parent = $post->post_parent;
if( $options['page_parent'] ) {
$post_parent = $options['page_parent'];
}
if ($rule['operator'] == "=="){
$match = ( $post_parent == $selected_post );
}
elseif ($rule['operator'] != "!="){
$match = ( $post_parent != $selected_post );
}
return $match;
}
Your Artist Collection field group is set to only appear on one post, the post Designer Post 1 which is a Designer Post type.
I don't understand what all the code is for? Just create a different field group for each post that needs a different field group and a separate rule for each.
Ok sorry I understand the issue now and I have recreated the issue on my local install.
On the line of code below you are looking for the post_parent but I think you should be looking for the ID.
I changed this:
$post_parent = $post->post_parent;
to this:
$post_parent = $post->ID;
and it's working for me.
If I understand your problem correctly, in wp-admin post edit page click on screen options on the upper right corner. In the menu that appears make sure the Custom fields is selected. This will make the custom fields appear for edit.

Specifying 'post_per_page' for multiple post loop

I have created a post loop that displays 2 different types of post ('portfolio' and 'post').
<?php
$work = array(
'post_type' => array('portfolio','post'),
'posts_per_page' => '8',
);
$loop = new WP_Query( $work );
while ( $loop->have_posts() ) : $loop->the_post();
if ( get_post_type() == 'portfolio' ) {
// My portfolio code will go here
}
else if ( get_post_type() == 'post' ) {
// My post code will go here
}
endwhile;
?>
This seems to work fine, but what I would like to do is limit the number of posts each type displays. I've set it so that it limits 8 overall but i'd like to expand this further and limit each type to 4 (4 + 4 = 8 overall).
Hey there I can not think of an easy solution but you have some possibilities to achieve this.
Query all posts and make a counter (bad performance if you have very much posts)
$work = array(
'post_type' => array('portfolio','post'),
'posts_per_page' => -1,
);
$count_portfolio = 0;
$count_post = 0;
$loop = new WP_Query( $work );
while ( $loop->have_posts() ) : $loop->the_post();
if ( get_post_type() == 'portfolio' && $count_portfolio < 4 ) {
$count_portfolio++;
}
else if ( get_post_type() == 'post' && $count_post < 4) {
$count_post++;
}
if($count_portfolio >=3 && $count_post >=3) {
break;
}
endwhile;
Make two different queries - one for the last four portfolios and one for the last 4 posts
// pseudo code
$allposts = array_merge($query1->posts, $query2->posts);
usort($allposts,'orderbydate_custom_function');
foreach($allposts as $post) {
// do output
}
Make a custom call with $wpdb to query exactly what you want

Wordpress, random product only on home search page

I have a custom wordpress search page with page navigation numbers, my client asks me to random products on page 1 but not for others, but all products displayed randomly on home page should not displayed on others pages.
For the query i have this code :
$args = array(
'post_type' => 'products',
'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 )
)
and for the random :
if( $args['paged'] == 1) {
$args['orderby'] = 'rand';
} else {
$args['order'] = 'DESC':
}
the results are there when i do a search, and first page random well, but some products that are already displayed on home page because of the random are also displayed on others pages (ex : page 2 ).
The aim is not display products that are already displayed on home page.
I already do something similar :
if( $page == 1 ) shuffle($r->posts);
But it shuffle only first the 10 products on page 1, and others products on others pages never display on page 1.
After some thoughts i think store first 10 random products to cookie or session and do a NOT IN for others pages ? like this ?
if( $args['paged'] == 1 ){
$args['orderby'] = 'rand';
$r = new Wp_Query($args);
$randomFirstPage = wp_list_pluck( $r->posts, 'ID' );
print_r($randomFirstPage);
setcookie( 'firstPageResults', $randomFirstPage, time()+3600, '/', 'mydomain.com/dev' );
}else{
$not_in = $_COOKIE['firstPageResults'];
$args['NOT IN'] = $not_in;
$r = new Wp_Query($args);
}
Sorry for bad english, and may you help me please ?
Thanks
Try this aproach:
<?php
$products1_ids = array();
$products2_ids = array();
$allproducts = get_posts(array('post_type' => 'products'));
$p=1; foreach($allproducts as $products) {
if(is_page(1) && $p<11) {
$products1_ids[] = $products->ID;
}
if(!is_page(1) && $p>10) {
$products1_ids[] = $products->ID;
}
$p++; }
shuffle($products1_ids);
shuffle($products2_ids);
$post_in = is_page(1) ? $products1_ids : $products2_ids;
$products = new WP_Query(array(
'post_type' => 'products',
'posts_per_page' => 10,
'post__in' => $post_in,
));
if($products->have_posts()) {
while($products->have_posts()) { $products->the_post();
echo '<div class="post">'
the_title();
echo '</div>';
}
}
Hope it helps
Your posted code above uses $args['NOT IN'] = $not_in;, but according to the WP_Query docs the argument to exclude posts by id is post__not_in:
$query = new WP_Query(
array('post_type' => 'post', 'post__not_in' => array(2, 5, 12, 14, 20))
);
So try:
$args['post__not_in'] = $not_in;

Rewrite Wordpress url in CUSTOM POST TYPE

I have horoscope post type, where I have 4 categories (yearly, monthly, lovely and weekly horoscope) every post have 12 editors - 12 signs.
I need that URL structure:
In Yearly I need this url: http://domain.com/post-type/taxonomy/year
In Monthly I need this url:
http://domain.com/post-type/taxonomy/month/year
In Lovely I need this url:
http://domain.com/post-type/taxonomy/month/year
In Weekly I need this url: http://domain.com/post-type/taxonomy
In Yearly I have many years, in monthly and lovely I have many years and many month, in weekly just on page that edit every week.
At first I think that "taxonomy" - it will be parent category of taxonomy, "month" - it will be child category of taxonomy and "year" - it will be post.
But when create in on taxonomy the same name of category their slug became "month-1, month-2" and the same when I create the same post name in post type.
So this solution doesn't work.
Now I want to create 4 post type and in each post type rewrite url, like that:
In Yearly I need that in url show:
http://domain.com/horoscope/post-type/year-of-post create and no slug of post
In Monthly and Lovely I need that in url show:
http://domain.com/horoscope/post-type/month-of-post-create/year-of-post-create/ and no slug of post
In weekly just: http://domain.com/horoscope/weekly/
Now I create 4 post type and rewrite url with this code:
global $wp_rewrite;
$kuukausihoroskooppi_structure = '/horoskoopit/kuukausihoroskooppi/%monthnum%/%year%/%kuukausihoroskooppi%';
$wp_rewrite->add_rewrite_tag("%kuukausihoroskooppi%", '([^/]+)', "kuukausihoroskooppi=");
$wp_rewrite->add_permastruct('kuukausihoroskooppi', $kuukausihoroskooppi_structure, false);
// Add filter to plugin init function
add_filter('post_type_link', 'kuukausihoroskooppi_permalink', 10, 3);
// Adapted from get_permalink function in wp-includes/link-template.php
function kuukausihoroskooppi_permalink($permalink, $post_id, $leavename) {
$post = get_post($post_id);
$rewritecode = array(
'%year%',
'%monthnum%',
'%day%',
'%hour%',
'%minute%',
'%second%',
$leavename? '' : '%postname%',
'%post_id%',
'%category%',
'%author%',
$leavename? '' : '%pagename%',
);
if ( '' != $permalink && !in_array($post->post_status, array('draft', 'pending', 'auto-draft')) ) {
$unixtime = strtotime($post->post_date);
$category = '';
if ( strpos($permalink, '%category%') !== false ) {
$cats = get_the_category($post->ID);
if ( $cats ) {
usort($cats, '_usort_terms_by_ID'); // order by ID
$category = $cats[0]->slug;
if ( $parent = $cats[0]->parent )
$category = get_category_parents($parent, false, '/', true) . $category;
}
// show default category in permalinks, without
// having to assign it explicitly
if ( empty($category) ) {
$default_category = get_category( get_option( 'default_category' ) );
$category = is_wp_error( $default_category ) ? '' : $default_category->slug;
}
}
$author = '';
if ( strpos($permalink, '%author%') !== false ) {
$authordata = get_userdata($post->post_author);
$author = $authordata->user_nicename;
}
$date = explode(" ",date_i18n('Y F d H i s', $unixtime));
$rewritereplace =
array(
$date[0],
$date[1],
$date[2],
$date[3],
$date[4],
$date[5],
$post->post_name,
$post->ID,
$category,
$author,
$post->post_name,
);
$permalink = str_replace($rewritecode, $rewritereplace, $permalink);
} else { // if they're not using the fancy permalink option
}
return $permalink;
}
For Yearly post type I don`t need %monthum% in my url so in that post type in code:
$kuukausihoroskooppi_structure = '/horoskoopit/kuukausihoroskooppi/%monthnum%/%year%/%kuukausihoroskooppi%';
I remove %month%/ and this post type work good with url http://domain.com/horoscope/post_type/year_of_post/post_slug with template: single-post_type.php
But I don`t need post-slug, so I remove %kuukausihoroskooppi%, but then this page show like archive.php;
But post type Monthly and Lovely wich url with %monthum% is redirect to 404 page and dont show.
What better to do?

get post by post name instead of id

Ok i have this code currently.
<?php
$post_id = 266;
echo "<div id='widgets-wrapper3'><div id='marginwidgets' style='overflow: auto; max- width: 100%; margin: 0 auto; border: none !important;'>";
$queried_post = get_post($post_id);
echo "<div class='thewidgets'>";
echo substr($queried_post->post_content, 0, 500);
echo "<a href='".get_permalink( 26 )."' title='Read the whole post' class='rm'>Read More</a>";
echo "</div>";
echo "</div></div>";
?>
As you can see to the above code, the routine is to get the post by ID, but my permalinks change into post name instead of post id for SEO purposes. How do I get the post by post name?
Hope someone here could figure it out. Thank you.
get_page_by_path()
WordPress has a built-in function that might help, with a few words of caution.
<?php get_page_by_path( $page_path, $output, $post_type ) ?>
Here's the relevant Codex entry.
To get a post, rather than a page, you just need to supply 'post' as the $post_type argument, and usually OBJECT (with no quotes) as the $output type, like this:
<?php get_page_by_path( 'my_post_slug', OBJECT, 'post' ) ?>
Note this function does not check the published or private status of the matched post. This is great if the item you're looking for is and attachment, but can be problematic for posts and pages (ie drafts, private posts etc.)
Note if it is a page you're looking for, and that page is hierarchical (ie: it has a parent), then you need to supply the entire path, that is: 'parent_page_slug/my_page_slug'.
WP_Query / get_posts()
If either of these are a problem for you, then you should consider just using the WP_Query class to get your post by name:
$found_post = null;
if ( $posts = get_posts( array(
'name' => 'my_post_slug',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1
) ) ) $found_post = $posts[0];
// Now, we can do something with $found_post
if ( ! is_null( $found_post ) ){
// do something with the post...
}
function get_post_by_name($post_name, $output = OBJECT) {
global $wpdb;
$post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type='post'", $post_name ));
if ( $post )
return get_post($post, $output);
return null;
}
Something this.
Use WP_Query. This function will retrieve the first post with the given name, or null if nothing is found:
function get_post_by_name(string $name, string $post_type = "post") {
$query = new WP_Query([
"post_type" => $post_type,
"name" => $name
]);
return $query->have_posts() ? reset($query->posts) : null;
}
By default this will search for an item of the type post:
get_post_by_name("my-post")
As a second argument you can set that to something else:
get_post_by_name("my-page", "page")

Categories