WordPress.org

Ready to get started?Download WordPress

Forums

how to query posts and auto assign category if post title has keyword (3 posts)

  1. neomatrix2
    Member
    Posted 2 years ago #

    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');
  2. neomatrix2
    Member
    Posted 2 years ago #

    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

  3. neomatrix2
    Member
    Posted 2 years ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic