0

I am trying to get a post from database with a post_title like %Weapon%.

I tried the code from bellow, but the single.php dies.

            $args = array(
                'numberposts'  => 20,
                'category'     => 4,
                'meta_query' => array(
                    array(
                    'key' => 'title',
                    'value' => "Weapon",
                    'compare' => 'LIKE'
                    )
                )
            );
            // $posts = get_posts($args);

            query_posts( $args );

I want to get posts from the database where the post_title is like %Weapon%.

Hillel
  • 811
  • 2
  • 7
  • 19
Smithy
  • 19
  • 1
  • 6
  • Possible duplicate of [WordPress get\_posts by title like](https://stackoverflow.com/questions/25103949/wordpress-get-posts-by-title-like) – Artem May 15 '19 at 12:51

2 Answers2

0

If to use "s"=>"Weapon" it will give you all posts that titles and contents contains "Weapon".

But if you want to get "title like" posts only, you need to add some SQL there.

$string="Weapon";
global $wpdb;
$theneededposts=$wpdb->get_col("SELECT ID FROM $wpdb->posts 
  WHERE post_title
  LIKE '%".esc_sql($string)."%' "
);
if (empty($theneededposts)) $theneededposts=array();
$args = array(
           'numberposts'  => 20,
            'category'     => 4,
            'post__in'=>$theneededposts,
           );
$posts = get_posts($args);
Elvin Haci
  • 3,503
  • 1
  • 17
  • 22
0

Hope that code below helpful for you

<?php 
    global $wpdb;
    $title = 'Weapon';
    $myposts = $wpdb->get_col( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_status = 'publish' AND  post_title LIKE '%s'", '%'. $wpdb->esc_like( $title ) .'%'  ) );

    foreach ( $myposts as $mypost ) 
    {
        $post = get_post( $mypost );
        //run your output code here
        echo $post->post_title;
    }
 ?>
SolverWp
  • 31
  • 3
  • Hello, Every information store in $post variable. Just to see all information about the post. You can display post content post_content; ?> in this way. – SolverWp Aug 19 '20 at 03:11