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")
Related
I have a custom post called 'project'.
I need to get 'titles' that logged in user wrote.
I tried the following code but it doesn't show any titles.
I'm a beginner... I looked into but I can't find which one has problems.
Would you please correct my code?
function output_projects_list() {
global $wpdb;
$custom_post_type = 'project'; // define your custom post type slug here
$current_user = get_userdata(get_current_user_id());
$current_user_name = $current_user->display_name;
// A sql query to return all the logged in users' post titles
$results = $wpdb->get_results( $wpdb->prepare( "
SELECT ID
, post_title
FROM {$wpdb->posts}
WHERE post_type = %s
, author = %s"
, and post_status = 'publish'
", $custom_post_type, $current_user_name ), ARRAY_A );
// Return null if we found no results
if ( ! $results )
return;
foreach( $results as $index => $post ) {
$output = $post['post_title'];
}
return $output;
}
echo output_projects_list();
Thank you.
I would use WP_Query instead, it's cleaner and easier to read. Take look at the following code:
function user_published_posts()
{
$query = new WP_Query(array(
"author" => get_current_user_id(),
"post_type" => "project",
"post_status" => "publish"
));
while ($query->have_posts()) {
$query->the_post(); ?>
<a href="<?php the_permalink(); ?>">
<h3><?php the_title(); ?></h3>
</a>
<span><?php the_author() ?></span>
<?php };
}
Let me know if it's what you're looking for!
What i want to make:
I want to make a navigation menu where every dropdownbar is its own post type.
Movie
movie1
movie2
Book
book1
book2
Game
game1
game2
What i've made so far:
I'm not the best at php yet, but i tried to work something out:
echo "<ul class="menu">";
$post_type = get_post_types( array('Movie', 'Book', 'Game') );
foreach( $post_type as $type ) {
$args = array(
'post_type' => $type
);
echo "<li>".$type."<ul class="dropdown">";
$posts = get_posts( $args );
if( $posts ) {
foreach( $posts as $post ) {
echo "<li>".get_the_title( $post->ID, 'title' )."</li>";
}
echo "</ul></li>";
}
}
echo "</ul>";
Question:
Is there a smarter way to make the dropdownmenu? or what can i do to make it work?
There's nothing wrong with that approach, except that you shouldn't use get_post_types() - just an array of the post type names will do.
As it stands at the moment, 'post_type' => $type will pass an array to post_type, when it should be a string.
Also, echo "<li>".$type."<ul class="dropdown">"; should be inside your if( $posts ) { before the foreach.
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;
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.
I have a webpage that I want to display images that are uploaded by a certain author.
In the backend if I look at media, each image has an 'Uploaded By' attribute, and then it says the authors name.
(source: discoveryourwonder.com)
I've tried using this loop:
<?php
// The Query
$args = array(
'author' => $author_name_variable, // Replace with author id
'post_status' => 'any',
'post_type' => 'attachment'
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . the_content() . '</li>';
}
echo '</ul>';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>
It is very buggy. Some authors it will show every media file, others none; the rest are just inaccurate. It's a real blind shot :/
The goal is to loop through all the media files, and then post the_content() of all files with the corresponding Uploaded By name.
I would be grateful if someone could comment as to why an ID is more reliable than a slug in the 'author' argument.
I figured out a solution. Apparently the 'author' argument does not like usernames, so I converted it to ID and it works now. I used get_user_by( 'slug', $username ); to get all the information of the particular username, and then assigned that array to a variable. I then filtered the variable to only use the ID and passed that through the arguments.
Here's the working loop:
<?php
// The Query
$profileid = get_user_by( 'slug', $username );
$args = array(
'author' => $profileid->id, // Replace with author id
'post_status' => 'inheret',
'post_type' => 'attachment'
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . the_content() . '</li>';
}
echo '</ul>';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>