search-extras.php 2.62 KB
<?php



add_action( 'add_attachment', 'add_attachment_mime_type' );
function add_attachment_mime_type( $attachment_id ){
   $post =  get_post( $attachment_id );
   $post_mime_type = explode(".", $post->_wp_attached_file);
   update_post_meta( $attachment_id, 'file_type', end($post_mime_type) );

}

function exclude_in_search_results( $query ) {
        
	if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
		
		$query->set( 'post_type', array(  'attachment',  'documents') );

		$query->set( 'meta_query', array (
			'relation' => 'OR',
			array (
				'relation' => 'AND',
				array(
					'key'     => 'exclude_from_search',
					'value'   => 1,
					'compare' => '!=',
				),
			),
		) );
		
		
	}
}
add_action( 'pre_get_posts', 'exclude_in_search_results' );

 // if(get_locale() == 'fr_FR') {
		// 	$query->set( 'meta_query', array (
		// 		'relation' => 'OR',
		// 		array (
		// 			'relation' => 'AND',
		// 			array(
		// 				'key'     => 'wpml',
		// 				'value'   => 'FR',
		// 				'compare' => '==',
		// 			),
		// 		),
		// 	) );

		// }else{
		// 	$query->set( 'meta_query', array (
		// 		'relation' => 'OR',
		// 		array (
		// 			'relation' => 'AND',
		// 			array(
		// 				'key'     => 'wpml',
		// 				'value'   => 'EN',
		// 				'compare' => '==',
		// 			),
		// 		),
		// 	) );
		// }


// apply tags to attachments 
function wptp_add_tags_to_attachments() {
	register_taxonomy_for_object_type( 'post_tag', 'attachment' );
}
add_action( 'init' , 'wptp_add_tags_to_attachments' );





add_action('init','set_exclude_from_search');
function set_exclude_from_search()
{ 
		if ($_GET['var'] =='set_wpml_from_search')  {
			global $post;
			$args = array( 'posts_per_page' => -1,  'post_type' => 'documents');

			$pages = get_posts( $args );
			error_log(print_r($pages,true));
			foreach ( $pages  as $page ){
				error_log($page->ID);
				update_post_meta($page->ID, 'wpml', "EN" );
			}
			$args = array( 'posts_per_page' => -1,  'post_type' => 'attachment');

			$pages = get_posts( $args );
			error_log(print_r($pages,true));
			foreach ( $pages  as $page ){
				error_log($page->ID);
				update_post_meta($page->ID, 'wpml', "EN" );
			}
		}
}

add_action('init','delete_exclude_from_search');
function delete_exclude_from_search()
{ 
		if ($_GET['var'] =='delete_wpml_from_search')  {
			$args = array( 'posts_per_page' => -1,  'post_type' => 'attachment');
			$pages = get_posts( $args );
			foreach ( $pages  as $page ){
				$exclude_from_search = get_post_meta($page->ID, 'exclude_from_search', true);
				if($exclude_from_search == '0'){
					wp_delete_attachment( $page->ID, true ); 
					//error_log($page->ID);
				}
			}
		}

}