Support » Fixing WordPress » how to query posts and auto assign category if post title has keyword

  • how can i query posts by current date and auto assign category based on keyword found on post title, something like if title contains ‘oranges’ auto assign it ‘oranges’ category

    maybe something like this which can go to functions.php

    function add_category_automatically($post_ID) {
    	global $wpdb,$post;
    
    $today = getdate();
    $query = new WP_Query( 'year=' . $today["year"] . '&monthnum=' . $today["mon"] . '&day=' . $today["mday"] );
    while ( $the_query->have_posts() ) : $the_query->the_post();
    
    $post_title = get_the_title();
    if (stripos($post_title, 'francisco')!==false) {
    		$cat = array(8);
    		wp_set_object_terms($post_ID, $cat, 'category');
    	}
    endwhile;
    }
    add_action('publish_post', 'add_category_automatically');
Viewing 2 replies - 1 through 2 (of 2 total)
  • i used ‘francisco’ as the keyword instead of ‘oranges’ up there in the code and cat id 8, to which i want to assign posts automatically

    Update:

    i am using this code now , it works if i publish a new post but doesnt work for existing posts??? ….. it should run every time and check all the posts in the database and auto categorize the post but smhw its not

    `add_action( ‘wp_insert_post’, ‘update_post_terms’ );
    function update_post_terms( $post_id ) {
    if ( $parent = wp_is_post_revision( $post_id ) )
    $post_id = $parent;
    $post = get_post( $post_id );
    if ( $post->post_type != ‘post’ )
    return;
    $post_title = get_the_title();
    if (stripos($post_title, ‘oranges’)!==false) {

    // add a category
    $categories = wp_get_post_categories( $post_id );
    $newcat = get_term_by( ‘name’, ‘oranges’, ‘category’ );
    array_push( $categories, $newcat->term_id );
    wp_set_post_categories( $post_id, $categories );
    }
    }`

    i know it will put a good load on my database even if i figure this out but i am looking for a way to do this like one instance every two hours or something like that, Please help!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘how to query posts and auto assign category if post title has keyword’ is closed to new replies.