Wordpress query posts by title issue - php

I'm using below code to get posts by title.
protected function get_post_by_title($post_title, $output = OBJECT, $post_type = 'post' )
{
global $wpdb;
$post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $post_title, $post_type ));
if ( $post )
return get_page($post, $output);
return null;
}
Everything is working fine, except it will not find the posts having single quote in title. Consider below as $post_title.
This is a test's post
$wpdb->prepare will return query something like below.
This is a test\\\'s post
Which will return no result. Can anyone please help me on this ?
Thanks in advance

You should never compare with the real title. Wordpress offers you the possibility to create slugs without all those weird characters like " " or "'". Then you can compare them:
Use sanitize_title() to create a slug from your title, and then you can compare them.

I think this should fix the issue,
DOC: http://in1.php.net/manual/en/mysqli.real-escape-string.php
protected function get_post_by_title($post_title, $output = OBJECT, $post_type = 'post' )
{
global $wpdb;
$post_title = mysqli_real_escape_string($post_title); //escape special meaning
$post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $post_title, $post_type ));
if ( $post )
return get_page($post, $output);
return null;
}
edit:
That might not work, try this,
$post_title = addslashes($post_title);
Let me know which one works for you.

Related

How to let users post only once for custom post type (php / wordpress)?

I need to let users only post once for custom post 'projects'.
The code below counts the number of the post:
$userid = get_current_user_id();
function count_user_posts_by_type($userid, $post_type = 'projects', $post_status = 'publish') {
global $wpdb;
$query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $userid AND post_type = '$post_type' AND post_status = '$post_status'";
$count = $wpdb->get_var($query);
return apply_filters('get_usernumposts', $count, $userid);
}
And shows correct number with
<?php echo count_user_posts_by_type($userid); ?>
My question:
I need to combine it with add_action.
So that when the result is 0 the user can post, when the result is !=0 the user cannot post.
The code below is something that I want to implement but it doesn't work at all and I have no idea how to combine together.
Would you please let me know how to combine codes together?
add_action( 'count-user-posts-by-type', 'count_user_posts_by_type' );
$postcount = count_user_posts_by_type($userid);
if($postcount != 0){
return ( 'www.mywebsite.com/cannot-post/' );
} else{
return ( 'www.mywebsite.com/can-post/' );
}
}
Thank you.
You can use is_user_logged_in() to check whether the current user is logged in or not.
Then you can use the template_redirect hook to perform the check :
function only_post_once_redirect()
{
if( is_user_logged_in() ) {
$userid = get_current_user_id(); //-- get the user id
$postcount = count_user_posts_by_type( $userid ); //-- get the count
if( $postcount != 0 ){ //-- not equal to zero
wp_redirect( home_url( 'www.mywebsite.com/cannot-post/' ) );
die;
} else{ //-- equal to zero
wp_redirect( home_url( 'www.mywebsite.com/can-post/' ) );
die;
}
}
}
add_action( 'template_redirect', 'only_post_once_redirect' );
You may need to add some more login to it, say to check which the user is now or something like that.
Or if you want this check & redirect to happen just after the login, you could try the login_redirect hook.
EDIT
I believe you have to spend some time polishing your PHP skills. Look for some basic PHP tutorials like this. You will recall everything after you spend an hour or two in those tutorials.
To answer your question(which you asked in comments), you can simply pass the second parameter as string. No need of that $post_type = part in it. Only in function definition (ie, when you define how the function should perform), you write the default values. When you make function calls, you simply pass the values as parameter. No need of the assignments in the parameters.
In short, your function call should be like this:
$postcount = count_user_posts_by_type( $userid2, 'projects' );
Since you've already mentioned the default value of the second parameter to be projects in your function definition, you can simply use this:
$postcount = count_user_posts_by_type( $userid2 );
I solved the problem using different code, in case someone needs it :
add_shortcode( 'current-user-has-posts' , 'current_user_has_posts' );
function current_user_has_posts(){
$args = array(
'post_type' => 'projects',
'author' => get_current_user_id(),
);
$wp_posts = get_posts($args);
if (count($wp_posts)) {
return ( 'www.mywebsite.com/cannot-post/' );
} else {
return ( 'www.mywebsite.com/can-post/' );
}
}

Include post title wordpress in replace SQL

I need something similar to this:
$titulo = get_the_title( $post_id );
update wp_posts set post_content =
replace(post_content,'>Episódio','>$titulo Episódio');
I know that this function is wrong, but it is a way of exemplifying what I need.
I need to get the title wordpress and use with the SQL replace function
Backup your database first before trying this. Add this to your theme's 'functions.php', run only once and delete. Please note that this will replace all occurrences of 'Episodio' with '[post title] Episodio'. Keep FTP in hand since you may not able to access 'functions.php' before deleting this code.
<?php
function replace_string()
{
global $wpdb;
$table_name = $wpdb->prefix . "posts";
$results = $wpdb->get_results ( "SELECT * FROM $table_name ORDER BY ID" );
foreach ( $results as $postobj )
{
$post_content = str_replace( 'Episodio', $postobj->post_title.' Episodio', $postobj->post_content);
$selectd = "UPDATE {$table_name} SET `post_content` = '".$post_content."' WHERE ID='".$postobj->ID."'";
$wpdb->get_results($selectd);
}
die();
}
add_action( 'after_setup_theme', 'replace_string' );
?>

PHP IF OR statement validation error

Im using the below code in order to add all Wordpress posts (excluding the 'sliders' category) to a category called 'Frontpage' ID = 28
function add_category_automatically1($post_ID) {
global $wpdb;
$postsWeWants = $wpdb->get_results("SELECT ID, post_author FROM $wpdb->posts where ID = $post_ID");
foreach ($postsWeWants as $postsWeWant) {
if (!in_category('sliders')) {
$cat = array(28, );
wp_set_object_terms($post_ID, $cat, 'category', true);
}
}
I want to add the exception of an additional category called 'business-information' but I can't get the OR operator to validate properly.
I was looking at using something like below
function add_category_automatically1($post_ID) {
global $wpdb;
$postsWeWants = $wpdb->get_results("SELECT ID, post_author FROM $wpdb->posts where ID = $post_ID");
foreach ($postsWeWants as $postsWeWant) {
if (!in_category('sliders')) OR (!in_category('business-information')) {
$cat = array(28, );
wp_set_object_terms($post_ID, $cat, 'category', true);
}
}
This:
if (!in_category('sliders')) OR (!in_category('business-information'))
// ^ -- ^ -- and here
is wrong. Because you close ) and open ( too early.
Proper code is:
if (!in_category('sliders') OR !in_category('business-information'))
And by the way such logic is invalid. If item is in 'business-information' then !in_category('sliders') true. I suppose you need to check for not existing in both cats:
if (!in_category('sliders') AND !in_category('business-information'))
You are using it wrong instead if (!in_category('sliders')) OR (!in_category('business-information')) {
write it like this (one more thing which is mentioned by #FirstOne you need to use AND instead OR to apply both conditions not one of them)
if( !in_category('sliders') AND !in_category('business-information') ) {
...
}
so that both !in_category checks will be in same if( ... ) scops

$_POST in array?

I have a script that put some terms into an array and then into the database.
Below you find a snippet. Everything is working fine, but i cannot get the $POST code to work correctly. What i need is that it contains the value of 'app' combined with the $album['id'] that is submitted by a form. I am pretty sure I am doing something wrong here. Can anyone help me out? Thanks.
global $wpdb;
$post_id = get_queried_object_id();
$post_author_id = get_post_field( 'post_author', $post_id );
$albums = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM wp_wppa_albums WHERE owner = "' . get_author_name( $post_author_id ) .'"' ), ARRAY_A );
$input_terms = array();
if ( $albums ) foreach( $albums as $album ) {
$input_terms[] = 'app_'.$_POST[$album['id']]; //This goes wrong
}
Whoops, my bad. Was an easy fix
$input_terms[] = sanitize_text_field($_POST['app_'.$album['id']]);
Worked for me!

Get WordPress Post ID from Post title

I have an issue with a custom WordPress theme I'm developing. It's a bit convoluted, but essentially, what I need to do is get a Post Id by it's Post Title. In pseudo-code it would ideally be something like:
title = "foo";
post_id = get_post_id_where_title_is(title);
The title mentioned is a static reference not being pulled in from WordPress, it's already present on the page.
Just a quick note for anyone who stumbles across this:
get_page_by_title() can now handle any post type.
The $post_type parameter has been added in WP 3.0.
Found a solution if anyone else struggles with this. Only posted the question out of desperation after 4 hours testing/Googling!
function get_post_by_title($page_title, $output = OBJECT) {
global $wpdb;
$post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='post'", $page_title ));
if ( $post )
return get_post($post, $output);
return null;
}
Found at: http://sudarmuthu.com/blog/2009/09/18/retrieving-posts-and-pages-based-on-title-in-wordpress.html
Like Michal Mau mentioned:
Use
$my_post = get_page_by_title( 'My Title', OBJECT, 'post' );
echo $my_post->post_content;
It's ( $page_title, $output, $post_type ) to easily receive a post instead of a page.
May this will help you more by creating function so that you need not to repeat the code
function get_page_id_by_title($title)
{
$page = get_page_by_title($title);
return $page->ID;
}
$title = "your title";
get_page_id_by_title($title);
you can use the following code as per [a link][http://codex.wordpress.org/Function_Reference/get_page_by_title]1 )!
<?php
$page = get_page_by_title( 'About' );
wp_list_pages( 'exclude=' . $page->ID );
?>
Another way to get the post and page ID, is to use a plugin..
there is a plugin, that what it simply does, is just add a column to your all pages, all posts, all categories tables, and have a column title of ID...and right below, you will see all the page/post id listed in that column..
I think that should be very useful..
I use this plugin very frequently and it is very lightweight.
http://getyourblogready.com/?p=758
No need to use any type of SQL querys or plugin, use Wordpress standard functions for this
$page = get_page_by_title( 'Home' );
$page_id = $page->ID;
it is easy to get the post id from post title using wp query:
global $wpdb;
$rw = $wpdb->get_row( $wpdb->prepare("select * from "your post table name" where post_title='your variable name or your post title'"));
echo $rw->ID;
1) differ post_title and post_name from each other. post_name maybe is the slug. post_title is the title of post.
2)
$titlee = "yourtitle";
echo $id = $wpdb->get_var("SELECT ID FROM $GLOBALS['wpdb']->posts WHERE post_name = $titlee");

Categories