Support

Account

Home Forums Search Search Results for 'pre_get_posts'

Search Results for 'pre_get_posts'

reply

  • You have a checkbox field, by this I’m assuming that this is a True/False field because you say "if it is true then that item is included in the loop"

    When you say that you want it included in the loop, here I’m assuming that you mean included in the posts that are returned by WP_Query, either the main query or a custom query.

    Is it a custom query or the main WP query that you are looking to alter to only include posts that are marked as true? My answer below is assuming that you mean the main WP query because you did not mention a custom query and "if it is true then that item is included in the loop"

    Let me know if I have any of this wrong.

    If my assumptions are correct then you need to add a pre_get_posts filter in WP.

    To your functions.php file add something like:

    
    // change "my_post_type" to the name of your post type
    // change "my_field" to the name of your ACF field
    function my_post_type_pre_get_posts($query) {
      if (is_admin() || !$query->is_main_query()) {
        return;
      }
      if ($query->query_vars['post_type'] == 'my_post_type') {
        $meta_query = array(
          array(
            'key' => 'my_field',
            'value' => '1' // this is the value that ACF saves
                           // for a true value in a true/false field
          )
        );
        $query->set('meta_query', $meta_query);
      }
    }
    add_action('pre_get_posts', 'my_post_type_pre_get_posts');
    
  • It looks like you have everything you need except a `pre_get_posts’ filter.

    I recently did this on a site I was working on. Basically, you need to add a filter.

    Here is the filter that I used:

    
        function reference_pre_get_posts($query) {
          // only in admin
          if (!is_admin() || !$query->is_main_query()) {
            return;
          }
          if ($query->query_vars['post_type'] == 'reference' && 
              ($orderby = $query->get('orderby'))) {
            switch ($orderby) {
              case 'featured':
              case 'reference_featured':
                $query->set('meta_key', 'reference_featured');
                $query->set('orderby', 'meta_value_num');
                break;
              default:
                // do nothing
                break;
            }
          } // end if reference and orderby
        }
    

    basically it test to see if we’re in the admin and if we are querying my post type and it it is one of the meta_keys I’ve set up as a sortable field. If it is then I add the meta_key that it needs to be ordered by and change the orderby to meta_value.

    Hope this helps

  • When you say,

    .. that does a simple loop through the ACF Gallery data structure and renders out a thumbnail gallery.

    makes me think you’re doing something outside of what a standard WP loop would do, so also outside any type of standard pagination that could be used, so it’s going to need to be custom built.

    As an alternate, and this is just a suggestion to think about, Don’t know how far you are into this thing, and it might be too far along to change plans, but, I would use a custom post type with an archive, use pre_get_posts to set up how many to show, and then use standard WP pagination and let WP take care of the details.

  • Hi,

    I don’t know if we are sharing the same issue (and for me, the issue stretches further back than 5.2.5) but I’ve figured out mine.

    The Context:

    The project I’m currently working on uses Polylang for translations. Custom fields aren’t set to be translated, their data is synced manually.

    I have a post object setup to retrieve posts from two custom post types: partner and sponsor. These post types aren’t configured to be multilingual.

    The Issue:

    In acf_field_post_object::render_field(), if there’s a saved value, ACF will retrieve all posts matching the saved value (in order to pre-populate the rendered field).

    
    $posts = acf_get_posts(array(
    	'post__in' => $field['value']
    ));
    

    Unfortunately, this returns an empty array because acf_get_posts() will default to loading from all available post types. In my case, acf_get_post_types() returns: post, page, attachment, partner, and sponsor.

    And this is the key problem: post and page are configured to be multilingual. This triggers Polylang to add a condition to fetch posts in the current language which the non-multilingual post types can’t fulfill.

    First Solution:

    Require ACF to pass along the filtered list of post types:

    
    $posts = acf_get_posts(array(
    	'post__in' => $field['value'],
    	'post_type' => $field['post_type']
    ));
    

    The one downside of this is if the list of filtered post types changes (e.g., a post type is removed), it will affect any currently saved value assigned to that now-removed post type.

    Second Solution:

    Intercept Polylang before it adds that language condition to the WP_query. I accomplish this using a backtrace to figure out if the WP_query was called by acf_get_posts() by way of acf_field->render_field().

    **Updated 2015-05-21T17:22-05:00**

    
    add_action( 'pre_get_posts', function ( &$wp_query ) {
    	$is_acf_get_posts = (
    		   ( $e = new Exception )
    		&& ( $trace = $e->getTraceAsString() )
    		&& false !== strpos( $trace, 'acf_get_posts(Array)' )
    		&& (
    			   (   is_admin() && false !== strpos( $trace, '->render_field(Array)' ) )
    			|| ( ! is_admin() && false !== strpos( $trace, '->format_value(' ) )
    		)
    	);
    
    	if ( $is_acf_get_posts && pll_is_not_translated_post_type( $wp_query->get('post_type') ) ) {
    		pll_remove_language_query_var( $wp_query );
    	}
    }, 9 );
    
    function pll_is_not_translated_post_type( $post_type ) {
    	global $polylang;
    
    	if ( isset( $polylang ) ) {
    		$pll_post_types = $polylang->model->get_translated_post_types( false );
    
    		return ( is_array( $post_type ) && array_diff( $post_type, $pll_post_types ) || in_array( $post_type, $pll_post_types ) );
    	}
    
    	return false;
    }
    
    function pll_remove_language_query_var( &$query ) {
    	$qv = &$query->query_vars;
    
    	unset( $qv['lang'] );
    
    	if ( ! empty( $qv['tax_query'] ) ) {
    		foreach ( $qv['tax_query'] as $i => $tax_query ) {
    			if ( isset( $tax_query['taxonomy'] ) && 'language' === $tax_query['taxonomy'] ) {
    				unset( $qv['tax_query'][ $i ] );
    			}
    		}
    	}
    }
    

    I made this filter very verbose just to make sure the idea is understand. I’m using a much more compact version in my project. This function can also be easily translated to your multilingual-plugin flavour (e.g., WPML).

    Cheers,

  • Hi @mmjaeger

    You could give this plugin a try: https://wordpress.org/plugins/search-everything/. I basically extends WP search functionality to include also the custom fields.

    Alternatively, you could hook a function to pre_get_posts action hook. In your function, first verify whether you are in the search page, if so, then proceed to create a meta query using the search input. Here are link to resources which will help you achieve this:
    https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
    https://codex.wordpress.org/Class_Reference/WP_Meta_Query

    Hope this helps 🙂

  • I removed any reference to pre_get_posts the best I could. I’ve made my theme able to drop the multilingual plugin I have activated for testing and I believe I found the issue.

    ACF 5.2.X is not compatible with PolyLang Version 1.7.2.

    Check out polylang/frontend/frontend-auto-translate.php; PLL_Frontend_Auto_Translate->pre_get_posts($query);

    https://wordpress.org/plugins/polylang/

  • Hi @jgraup

    Perhaps your theme / plugin contains some pre_get_posts filters which are modifying ACF’s get_posts function?

    There has been a minor change to the acf_get_posts function in that it does not use get_post anymore, instead it only uses get_posts.

    This could explain how a filter may be altering the query args and preventing the correct data from being returned.

  • You can add this to your functions.php to restrict shown media to the items owned by the current user:

    add_action('pre_get_posts','my_restrict_media_library');
    function my_restrict_media_library( $wp_query_obj ) {
    
    global $current_user, $pagenow;
    
    if( !is_a( $current_user, 'WP_User') )
    
    return;
    
    if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
    
    return;
    
    if( !current_user_can('edit_files') )
    
    $wp_query_obj->set('author', $current_user->ID );
    
    return;
    
    }
    
  • Hi,
    doesn’t work.

    in function.php:
    add_action(‘pre_get_posts’, ‘my_pre_get_posts’);

    function my_pre_get_posts( $query )
    {
    // validate
    if( is_admin() )
    {
    return;
    }

    if( !$query->is_main_query() )
    {
    return;
    }

    $meta_query = $query->get(‘meta_query’);
    if( !empty($_GET[‘auswahl’]) )
    {
    $bedrooms = explode(‘,’, $_GET[‘auswahl’]);

    //Add our meta query to the original meta queries
    $meta_query[] = array(
    ‘key’ => ‘p_reihe’,
    ‘value’ => $bedrooms,
    ‘compare’ => ‘IN’,
    );

    $bathrooms = explode(‘,’, $_GET[‘bathrooms’]);
    $meta_query[] = array(
    ‘key’ => ‘p_energieklasse’,
    ‘value’ => $bathrooms,
    ‘compare’ => ‘IN’,
    );
    }

    // update the meta query args
    $query->set(‘meta_query’, $meta_query);

    // always return
    return;

    }

    in archive.php:

    <div id=”search-houses”>
    <?php
    $field = get_field_object(‘p_reihe’);
    $values = isset($_GET[‘p_reihe’]) ? explode(‘,’, $_GET[‘p_reihe’]) : array();
    ?>

      <?php foreach( $field[‘choices’] as $choice_value => $choice_label ): ?>

    • <input type=”checkbox” value=”<?php echo $choice_value; ?>” <?php if( in_array($choice_value, $values) ): ?>checked=”checked”<?php endif; ?> /> <?php echo $choice_label; ?>
    • <?php endforeach; ?>

      <?php
      $field = get_field_object(‘p_energieklasse’);
      $values = isset($_GET[‘p_energieklasse’]) ? explode(‘,’, $_GET[‘p_energieklasse’]) : array();
      ?>
      <?php foreach( $field[‘choices’] as $choice_value => $choice_label ): ?>

    • <input type=”checkbox” value=”<?php echo $choice_value; ?>” <?php if( in_array($choice_value, $values) ): ?>checked=”checked”<?php endif; ?> /> <?php echo $choice_label; ?>
    • <?php endforeach; ?>

    </div>
    <script type=”text/javascript”>
    (function($) {

    $(‘#search-houses’).on(‘change’, ‘input[type=”checkbox”]’, function(){

    // vars
    var $ul = $(this).closest(‘ul’),
    vals = [];

    $ul.find(‘input:checked’).each(function(){

    vals.push( $(this).val() );

    });

    vals = vals.join(“,”);

    window.location.replace(‘http://www.jemaniblue.ch/kategorie/handbrausen/?auswahl=&#8217; + vals);

    console.log( vals );

    });

    })(jQuery);
    </script>

  • After more Googling around, I found this:

    http://support.advancedcustomfields.com/forums/topic/repeater-field-broken-when-using-category-php-file/

    I already had something similar in my functions.php, but it obviously wasn’t quite right. This is the correct code:

    //Include CPT In Categories Pages
    function namespace_add_custom_types( $query ) {
        if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
            $post_types = get_post_types( '', 'names' ); 
            $query->set( 'post_type', $post_types);
            return $query;
        }
    }
    add_filter( 'pre_get_posts', 'namespace_add_custom_types');

    Still, respect for the help ractoon!

  • @Elliot, The dump would only return single field but I was able to fix the problem.

    The problem was due to the use of pre_get_posts action in the functions.php so I had to disable it to fix the problem.

  • Sure,

    I call this in my custom plugin..

    
    /* acf post generate */
    
    function create_acf_post( $post_id )
    {
        // check if this is to be a new post
        if( $post_id != 'new' )
        {
            return $post_id;
        }
    
        // Create a new post
        $mytitle = get_user_meta( get_current_user_id(), 'nickname', true ) . ' - ' . $_POST['fields']['field_547959d79b64c'];
        $post = array(
            'post_status'  => 'draft' ,
            'post_title'  => $mytitle,
            'post_type'  => 'ifcc'
        );  
    
        // insert the post
        $post_id = wp_insert_post( $post );
    
        // update $_POST['return']
        $_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );    
    
        $user_id = get_current_user_id();
        update_user_meta( $user_id, 'done_free', '1' );     
        // wp_redirect('/');
    
        // return the new ID
        return $post_id;
    }
    
    add_filter('acf/pre_save_post' , 'create_acf_post' );
    

    and that is fired on frontend while after couple of pars are meet,, frontend, is single, is custom post (ifcc) and logged in..

    
    // =============================
    // frontend single ifcc logic 
    // =============================
    
    function cpt_front($query) {
        if ( !is_admin() && $query->is_main_query() ) {
            if ($query->is_single() && $query->post_type == 'ifcc' ) {
                if( is_user_logged_in() ){
                    $user_id = get_current_user_id();
                    $usernick = get_user_meta( $user_id, 'nickname', true );
                    update_field('submitee_name', $usernick);
                    $free = get_user_meta( $user_id, 'done_free', true );
                    if( $free == '1' ){
                        echo 'need to buy additional licence';
                    } else {
                        get_template_part( 'content', get_post_format() );
                        $args = array(
                            'post_id' => 'new',
                            'field_groups' => array( 68 )
                        );
                        acf_form( $args );
                    }
                } else {
                    // echo get_permalink( get_option('woocommerce_myaccount_page_id') );
                    echo do_shortcode('[woocommerce_my_account]');
                }
            }
        }
    }
    
    add_action('pre_get_posts','cpt_front');
    

    so, everything works cool, and post is inserted in backend and all, but redirect part if off somehow,,

    thanks

  • Ok, finally got it sorted…
    For anyone else out there that might run into this problem here’s the solution.
    Just add the following to your functions.php file.

    
    //Include CPT In Categories Pages
    function namespace_add_custom_types( $query ) {
        if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
            $post_types = get_post_types( '', 'names' ); 
            $query->set( 'post_type', $post_types);
            return $query;
        }
    }
    add_filter( 'pre_get_posts', 'namespace_add_custom_types');
    
  • Thank you, can not imagine what relief dates when you solve a problem that blocks an entire project like mine.

    To put chronicle the complete function for this specific use.

    • my custom post archive : ‘newstand’
    • my custom field: ‘newstand_selettore_stand’ (Object post one choose or multi choose for only custom post “stand”)
    • a ID value for a stand custom post exemple : 3640

    Result on the URL of site:
    my url for archive page: http://mydomain.com/newstand/?newstand_selettore_stand=3640

    The function:

    
    function my_pre_get_posts_newstand( $query ) {
        // validate
        if( is_admin() )               { return; }
        if( !$query->is_main_query() ) { return; }
    
        // get original meta query
        $meta_query = $query->get('meta_query');
        
            // allow the url to alter the query
            // eg: http://www.website.com/events?location=melbourne
            // eg: http://www.website.com/events?location=sydney
            // eg  http://www.luccafan/newstand/?newstand_selettore_stand=3640
            if( !empty($_GET['newstand_selettore_stand']) ){
                    $newstand_selettore_stand = explode(',', $_GET['newstand_selettore_stand']);
                    if( !empty($newstand_selettore_stand) ) {
                        foreach( $newstand_selettore_stand as $id ) {
                                $meta_query[] = array(
                                    'key'       => 'newstand_selettore_stand',
                                    'value'     => $id,
                                    'compare'   => 'LIKE',
                                );
                        }
                    }
            }// end of !empty($_GET['newstand_selettore_stand'])
    
        // update the meta query args
        $query->set('meta_query', $meta_query);
    
        // always return
        return;
    
    }
    add_action('pre_get_posts', 'my_pre_get_posts_newstand');
  • I think I got this solved.

    I have created the fields with the Admin user (user_id == 1) and the field appeared when I modified the query to include the Admin user_id. Here is the code I’m using now to prevent other users from seeing others posts and displays the fields on post.php page.

    
    add_filter('pre_get_posts', function($query) {
    
        if ($query->is_admin) {
            global $user_ID;
            global $pagenow;
    
            $allowedPages = ['post.php', 'post-new.php', 'admin-ajax.php'];
    
            if (in_array($pagenow, $allowedPages)) {
                $query->set('author__in', [$user_ID, 1]);
            } else {
                $query->set('author', $user_ID);
            }
        }
    
        return $query;
    
    });
    
    
  • Hmm… I enabled WP debug and I saw this appear repeatedly throughout the site:

    Notice: is_main_query was called incorrectly. In pre_get_posts, use the WP_Query::is_main_query() method, not the is_main_query() function. See http://codex.wordpress.org/Function_Reference/is_main_query. Please see Debugging in WordPress for more information. (This message was added in version 3.7.) in /home/onestopmods/public_html/wp-includes/functions.php on line 3245
    

    I deactivated the plugin, but I couldn’t access the site after that because of a get_field error (I assume this is normal if the plugin is deactivated) so I can’t really say if the plugin is the one causing this.

    Also, if debug mode is on and if the plugin is enabled, I’m unable to even click “submit”.

    Here’s the code for my “Add Post” page:

    <?php 
    /*
    Template Name: Add Post
    */
    acf_form_head();
    get_header(); 
    $specat = $_GET['cat'];
    	if($specat == 2){$namecat = Minecraft;}
    ?>
    
    <div id="main" class="full-width"><div class="wrap cf">
    
    	<div id="content" role="main">
    	
    		<?php while (have_posts()) : the_post(); ?>
    		<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
    			<h1 class="page-title">Submitting a Mod for: <?php echo $namecat; ?></h1>
    
    			<div class="page-content rich-content">
    			<?php 
    			if($specat == 2){$specicat = 1193;}
    			acf_form(array(
    					'post_title' => true,
    					'post_content' => true,
    					'post_id'		=> 'new_post',
    					'new_post'		=> array(
    						'post_title'  => 'New Post',
    						'post_type'		=> 'post',
    						'post_status'		=> 'pending',
    						'post_category'  => array("$specat") ,
    					),
    					'field_groups' => array( 1185, 1191, $specicat, 1197, 1200),
    					'submit_value'	=> 'Submit Your Mod',
    					'return' => 'http://onestopmods.com/view-mods/',
    				)); ?>
    			</div>
    		</div><!--end .hentry-->
    		<?php endwhile; ?>
    		
    	</div><!--end #content-->
    
    </div></div><!-- end #main -->
    
    <?php get_footer(); ?>
  • Thank you VoiD2008.
    I don’t have any other plugins, but I added some lines (see below) to functions.php myself, in order to get the custom post types displayed in the main query.
    I commented this out and all was normal again.
    But still, I need the functionality of the code snippet. Any ideas?

    This was the code that provoked the problem:

    add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
    
    function add_my_post_types_to_query( $query ) {
      if ($query->is_main_query() )
        $query->set( 'post_type', array('commissionedproject', 'alexaproject') );
      return $query;
    }
  • I solved it, for the most part. Here’s what worked for me:

    
    /*--------------------------------------------------------------------------------------
        *
        * Filter the query using the rules
        *
        *-------------------------------------------------------------------------------------*/
    
    // Get all the rules that have a taxonomy term that match the visitor's GEO-IP-detected country 
    function get_relevent_rules() {
         $args = array(
            'numberposts' => '-1',
    	    'post_type'   => 'display_rule',
            'tax_query'   => array(
                array(
                    'taxonomy' => 'my_taxonomy',
                    'terms' => 'A_GLOBAL_SET_ELSEWHERE_TO_THE_VISITORS_COUNTRY_OF_ORIGIN',      
                    'field' => 'slug',
                )
            )
        );
        $return = array();
        foreach (wp_list_pluck( get_posts($args), 'ID') as $id) {
            $return[] = array(
                        'key'       => 'display_rules',
                        'value'     => '"' . $id . '"',
                        'compare'   => 'NOT LIKE',
                    );
        }
        return $return;
    }
    
    // Change the main query to exclude any posts with a relationship field keyed 'display_rules' which includes any of the display rules containing our visitor's country.
     function only_in_countries($query) {
        if ($query->is_main_query()) {
            $query->set( 'meta_query', get_relevent_rules()
                
               
            );
        }
    }
    
    if( ! is_admin()) { add_action('pre_get_posts', 'only_in_countries'); } 
    
  • Got the very same problem with 4.3.8, but only for other user roles than administrators. I use the following code to achieve that the users can only edit their own posts:

    
    add_action('pre_get_posts', 'query_set_only_author' );
    	function query_set_only_author( $wp_query ) {
    		$screen = get_current_screen();
    
    		if ($screen->base === 'post')
    	    		return $query; // From ACF Support Forum
    
    	    global $current_user;
    	    if( is_admin() && !current_user_can('edit_others_veranstaltungen') ) {
    	        $wp_query->set( 'author', $current_user->ID );
    	        add_filter('views_edit-veranstaltung', 'fix_veranstaltungen_counts');
    	    }
    	}

    Any ideas to fix that problem? I searched the ACF js but it didn’t help me.

  • Okay, I finally figured this out on my own. I studied the get_field_object() function more deeply, and on this documentation page, in the “field_key vs field_name” section, there is a hint. It is not said directly, but apparently even if posts have been created that use the Field Group, if a filter causes the current query of posts (using the pre_get_posts hook) to return none of them, field_name won’t work. Even Elliot used the field_name in his tutorial, but in the case of a filter like this, you MUST use the field_key, even though it makes the code harder to read.

  • Hi @uakz

    Your pre_get_posts filter has the potential to affect every WP_Query on the page! This would explain why your top menu is not returning the correct data.

    Looking at the WP docs: http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts it seems that another validation is done in the filter to make sure this is the main query on the page:

    if ( !is_admin() && $query->is_main_query() ) {

    So you could add another line to the top of your filter like this:

    // validate if( !$query->is_main_query() ) { return; }

    hope that helps

  • for the form its

    the code bellow

    <?php
    /**
     * Template Name:create memorial Template
     *
     * @package WooFramework
     * @subpackage Template
     */
    
    acf_form_head();
     
    get_header(); ?>
    
        <!-- #content Starts -->
    <?php woo_content_before(); ?>
        <div id="content" class="col-full">
        
        <div id="main-sidebar-container">    
    
                <!-- #main Starts -->
                <?php woo_main_before(); ?>        
    
     
    	<div id="primary">
    		<div id="content" role="main">
     
    			<?php the_post(); ?>
     
    			<?php acf_form( $options ); ?>
     
    		</div><!-- #content -->
    	</div><!-- #primary -->
     
    <?php get_sidebar(); ?>
    <?php get_footer(); ?>
                       
    <?php
    woo_loop_before();
    if (have_posts()) { $count = 0;
    while (have_posts()) { the_post(); $count++;
    woo_get_template_part( 'content', 'page' ); // Get the page content template file, contextually.
    }
    }
    woo_loop_after();
    ?>     
                </section><!-- /#main -->
                <?php woo_main_after(); ?>
        
                <?php get_sidebar(); ?>
    
    </div><!-- /#main-sidebar-container -->         
    
    <?php get_sidebar( 'alt' ); ?>
    
        </div><!-- /#content -->
    <?php woo_content_after(); ?>
    
    <?php get_footer(); ?>

    the single memorial code

    <?php
    /**
     * Template Name:create memorial Template
     *
     * @package WooFramework
     * @subpackage Template
     */
    the_post();
    
    $template = get_field('template', $post->ID);
    if (empty($template)) {
        $template = 'standard';
    }
    $template_dir = get_stylesheet_directory() . '/memorials';
    $template_uri = get_stylesheet_directory_uri() . '/memorials';
    $templateFile = $template_dir . '/' . strtolower($template) . '.php';
    if (file_exists($templateFile)) {
        include($templateFile);
    }
    

    and the custom post type plugin

    ?php
    
    /*
      Plugin Name: Lvd4Evr - Memorial Custom Post Type
      Plugin URI:
      Description:
      Version: 1.0.0
      Author: Kathryn Reeve
      Author URI: http://BinaryKitten.com
      License: GPLv2
     */
    
           
    
    class j20_lovedforever_memorial
    {
    
        public function __construct()
        {
            add_action('init', array($this, 'create_post_type'), 0);
            $this->addAcf();
        }
    
        function create_post_type()
        {
    
            $labels = array(
                'name' => _x('Memorials', 'Post Type General Name', 'text_domain'),
                'singular_name' => _x('Memorial', 'Post Type Singular Name', 'text_domain'),
                'menu_name' => __('Memorial', 'text_domain'),
                'parent_item_colon' => __('Parent Memorial:', 'text_domain'),
                'all_items' => __('All Memorials', 'text_domain'),
                'view_item' => __('View Memorial', 'text_domain'),
                'add_new_item' => __('Add New Memorial', 'text_domain'),
                'add_new' => __('Add New Memorial', 'text_domain'),
                'edit_item' => __('Edit Memorial', 'text_domain'),
                'update_item' => __('Update Memorial', 'text_domain'),
                'search_items' => __('Search Memorials', 'text_domain'),
                'not_found' => __('No Memorial Found', 'text_domain'),
                'not_found_in_trash' => __('Memorial not found in Trash', 'text_domain'),
            );
            $rewrite = array(
                'slug' => 'memorial',
                'with_front' => true,
                'pages' => false,
                'feeds' => false,
            );
            $args = array(
                'label' => __('memorial', 'text_domain'),
                'description' => __('Memorial Pages', 'text_domain'),
                'labels' => $labels,
                'supports' => array('title', 'author','comments'),
                'taxonomies' => array('category', 'memorial'),
                'hierarchical' => false,
                'public' => true,
                'show_ui' => true,
                'show_in_menu' => true,
                'show_in_nav_menus' => true,
                'show_in_admin_bar' => true,
                'menu_position' => 20,
                'menu_icon' => '',
                'can_export' => true,
                'has_archive' => true,
                'exclude_from_search' => false,
                'publicly_queryable' => true,
                'rewrite' => $rewrite,
                'capability_type' => 'page',
            );
    
            register_post_type('memorial', $args);
    
            register_post_type( 'tribute',
                array(
                    'labels' => array(
                        'name' => __( 'Tributes' ),
                        'singular_name' => __( 'tribute' )
                    ),
                    'public' => true,
                    'has_archive' => true,
                    'rewrite' => array('slug' => 'tribute'),
                )
            );
    
            register_post_type( 'stories',
                array(
                    'labels' => array(
                        'name' => __( 'stories' ),
                        'singular_name' => __( 'stories' )
                    ),
                    'public' => true,
                    'has_archive' => true,
                    'rewrite' => array('slug' => 'stories'),
                )
            );
    
            register_post_type( '_user_video',
                array(
                    'labels' => array(
                        'name' => __( 'Video' ),
                        'singular_name' => __( 'video' )
                    ),
                    'public' => true,
                    'has_archive' => true,
                    'rewrite' => array('slug' => 'video'),
                )
            );
        }
    
        public function addAcf() {
         //   include plugin_dir_path(__FILE__) . DIRECTORY_SEPARATOR . 'acf.php';
        }
    
    }
    
    new j20_lovedforever_memorial();
    
    function my_pre_save_post( $post_id )
    {
        
        
        
        // Create a new post
        $post = array(
            'post_status'  => 'publish' ,
            'post_title'  =>  $_POST['title'],
            'post_type'  => 'memorial' ,
        );  
      
      
        if(get_post($id)) {
            $post_id = wp_update_post( get_post($post_id) );  
        } else {
            $post_id = wp_insert_post( $post );  
        };
        // insert the post
       
       
    
        // update $_POST['return']
        $_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );    
     
        // return the new ID
        return $post_id;
    }
    
     
    add_filter('acf/pre_save_post' , 'my_pre_save_post' );
    
    add_action('init', 'process_choose_template');
    
    function process_choose_template(){
     if(isset($_POST['choose-template'])) {
        $template = $_POST['template'];
        $post_id = $_POST['post_id'];
        add_post_meta(  $post_id , 'memorial_template', $template, true ) || update_post_meta(  $post_id , 'memorial_template', $template );
        wp_redirect( get_permalink($post_id) ); 
        exit(); 
     }
    }
    
    function memorial_save_post_class_meta($post_id, $post ) {
        if (get_post_type( $post ) == 'memorial'){
            $template = $_POST['template'];
            add_post_meta(  $post_id , 'memorial_template', $template, true ) || update_post_meta(  $post_id , 'memorial_template', $template );
    
        }
    }
    
    /* Fire our meta box setup function on the post editor screen. */
    
    //Meta Box 
    /* Meta box setup function. */
    function memorial_post_meta_boxes_setup() {
    
        /* Add meta boxes on the 'add_meta_boxes' hook. */
        add_action( 'add_meta_boxes', 'memorial_add_post_meta_boxes' );
    
        /* Save post meta on the 'save_post' hook. */
        add_action( 'save_post', 'memorial_save_post_class_meta', 10, 2 );
    }
    
    /* Create one or more meta boxes to be displayed on the post editor screen. */
    function memorial_add_post_meta_boxes() {
    
        add_meta_box(
            'memorial-post-class',          // Unique ID
            'Templates',      // Title
            'memorial_post_class_meta_box',     // Callback function
            'memorial',                 // Admin page (or post type)
            'side',                 // Context
            'default'                   // Priority
        );
    }
    
    function memorial_post_class_meta_box( $object, $box ) { ?>
        <?php $value = get_post_meta( $object->ID, 'memorial_template', true )?>
    
        <div>
            <label for=''>Template 1</label>
            <div class='chose-template-input'><input type='radio' name='template' value='1'  <?php echo ($value  == '1'|| $value  == '' ? 'checked="checked"' : '');?>></div>
        </div>
         <div>
            <label for=''>Template 2</label>
            <div class='chose-template-input'><input type='radio' name='template' value='2' <?php echo ($value  == '2' ? 'checked="checked"' : '');?>></div>
        </div>
         <div>
           <label for=''>Template 3</label>
            <div class='chose-template-input'><input type='radio' name='template' value='3' <?php echo ($value  == '3' ? 'checked="checked"' : '');?>></div>
        </div>
                     
                            
     <?php }            
    
    add_action( 'load-post.php', 'memorial_post_meta_boxes_setup' );
    add_action( 'load-post-new.php', 'memorial_post_meta_boxes_setup' );
    
        // Disable Admin Bar for everyone but administrators
    if (!function_exists('df_disable_admin_bar')) {
    
        function df_disable_admin_bar() {
            
            if (!current_user_can('manage_options')) {
            
                // for the admin page
                remove_action('admin_footer', 'wp_admin_bar_render', 1000);
                // for the front-end
                remove_action('wp_footer', 'wp_admin_bar_render', 1000);
                
                // css override for the admin page
                function remove_admin_bar_style_backend() { 
                    echo '<style>body.admin-bar #wpcontent, body.admin-bar #adminmenu { padding-top: 0px !important; }</style>';
                }     
                add_filter('admin_head','remove_admin_bar_style_backend');
                
                // css override for the frontend
                function remove_admin_bar_style_frontend() {
                    echo '<style type="text/css" media="screen">
                    html { margin-top: 0px !important; }
                    * html body { margin-top: 0px !important; }
                    </style>';
                }
                add_filter('wp_head','remove_admin_bar_style_frontend', 99);
                
            }
        }
    }
    
    //add_action('init','df_disable_admin_bar');
    
    add_action('pre_get_posts','ml_restrict_media_library');
    
    function ml_restrict_media_library( $wp_query_obj ) {
        global $current_user, $pagenow;
        if( !is_a( $current_user, 'WP_User') )
        return;
        if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
        return;
        if( !current_user_can('manage_media_library') )
        $wp_query_obj->set('author', $current_user->ID );
        return;
    }
    
    function tribute() {
      
        if(isset($_POST['submit_tribute'])){
              global $current_user;
              get_currentuserinfo();
            $post = $_POST['post_id'];
           $new_post = array(
                    'post_title' => $current_user->display_name,
                    'post_content' => $_POST['copy'],
                    'post_status' => 'publish',
                    'post_date' => date('Y-m-d H:i:s'),
                    'post_author' => $current_user->ID,
                    'post_type' => 'tribute',
                    'post_category' => array(0)
                    );
    
                   
            $post_id = wp_insert_post($new_post);
                add_post_meta(  $post_id , 'memorial_id', $post, true ) || update_post_meta(  $post_id , 'memorial_id', $post );
              wp_redirect( get_permalink($post) ); 
            exit(); 
        }
     
    }
    add_action('init','tribute');
    
    function stories() {
      
        if(isset($_POST['submit_Stories'])){
              global $current_user;
              get_currentuserinfo();
            $post = $_POST['post_id'];
           $new_post = array(
                    'post_title' => $current_user->display_name,
                    'post_content' => $_POST['copy'],
                    'post_status' => 'publish',
                    'post_date' => date('Y-m-d H:i:s'),
                    'post_author' => $current_user->ID,
                    'post_type' => 'stories',
                    'post_category' => array(0)
                    );
    
                   
            $post_id = wp_insert_post($new_post);
                add_post_meta(  $post_id , 'memorial_id', $post, true ) || update_post_meta(  $post_id , 'memorial_id', $post );
              wp_redirect( get_permalink($post) ); 
            exit(); 
        }
     
    }
    add_action('init','stories');
    
    function video() {
    
        if(isset($_POST['submit_video'])){
            global $current_user;
              get_currentuserinfo();
            $post = $_POST['post_id'];
           $new_post = array(
                    'post_title' => $current_user->display_name." ".$_POST['embed'],
                    'post_content' => $_POST['embed'],
                    'post_status' => 'publish',
                    'post_date' => date('Y-m-d H:i:s'),
                    'post_author' => $current_user->ID,
                    'post_type' => '_user_video',
                    'post_category' => array(0)
                    );
    
            $info = video_image($_POST['embed']);      
            $post_id = wp_insert_post($new_post);;
            update_field( 'video', $_POST['embed'], $post_id  );  
            update_field('image_url', $info, $post_id  );  
            add_post_meta(  $post_id , 'memorial_id', $post, true ) || update_post_meta(  $post_id , 'memorial_id', $post );  
            wp_redirect( get_permalink($post) ); 
            
        }
     
    }
    
    add_action('init','video');
    
    function video_image($url){
        $image_url = parse_url('http://'.$url);
        if($image_url['host'] == 'www.youtube.com' || $image_url['host'] == 'youtube.com'){
            $array = explode("&", $image_url['query']);
            return "http://img.youtube.com/vi/".substr($array[0], 2)."/0.jpg";
        } else if($image_url['host'] == 'www.vimeo.com' || $image_url['host'] == 'vimeo.com'){
            $hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/".substr($image_url['path'], 1).".php"));
            return $hash[0]["thumbnail_small"];
        }
    }

    I hope this helps if you need any more info i can provide this

  • Hi @lewmaster

    The first thing I noticed is that your pre_get_posts filter uses this code:

    
    $bedrooms = explode('|', $_GET['bedrooms']);
    

    This should be:

    
    $bedrooms = explode(',', $_GET['bedrooms']);
    

    Please debug your code line by line to make sure all variables are correct and that your output is as desired.

    Thanks
    E

  • Ok so I went through that tutorial – bedrooms was already one of the fields I need to sort by, so I thought it would be easy – however, I am having a lot of trouble with this still.

    This is the code I put in my functions file:

    add_action('pre_get_posts', 'my_pre_get_posts');
     
    function my_pre_get_posts( $query ) {
    
        if( is_admin() ) { return; }
     
        $meta_query = $query->get('meta_query'); // get original meta query
        
        
        // validate type
        if( empty($_GET['bedrooms']) )
        {
    	    return;
        }
        
        
        // get types as an array
        // - use explode to get an array of values from type=a|b|c
        $bedrooms = explode('|', $_GET['bedrooms']);
        
        
        // set compare for the meta_query
        // - http://codex.wordpress.org/Class_Reference/WP_Query
        $meta_query['relation'] = 'OR';
        
        
        foreach( $bedrooms as $bedroom )
        {
    	    $meta_query[] = array(
                'key'       => 'bedrooms',
                'value'     => '"' . $bedroom . '"',
                'compare'   => 'LIKE',
            );
        }
    	
    	
        $query->set('meta_query', $meta_query); // update the meta query args
        
        return; // always return
    }
    

    This is the code I have on the page I want to have filtering:

    <div id="search-houses">
    <?php 
     
    	$field = get_field_object('bedrooms');
    	$values = explode(',', $_GET['bedrooms']);
     
    	?>
    	<ul>
    		<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
    			<li>
    				<input type="checkbox" value="<?php echo $choice_value; ?>" <?php if( in_array($choice_value, $values) ): ?>checked="checked"<?php endif; ?> /> <?php echo $choice_label; ?></li>
    			</li>
    		<?php endforeach; ?>
    	</ul>
    </div>
    <script type="text/javascript">
    (function($) {
     
    	$('#search-houses').on('change', 'input[type="checkbox"]', function(){
     
    		// vars
    		var $ul = $(this).closest('ul'),
    			vals = [];
     
    		$ul.find('input:checked').each(function(){
     
    			vals.push( $(this).val() );
     
    		});
     
    		vals = vals.join(",");
     
    		window.location.replace('<?php echo home_url('find-my-apartment'); ?>?bedrooms=' + vals);
     
    		console.log( vals );
     
    	});
     
    })(jQuery);	
    </script>
    

    This is the page: http://tlc.mainteractivegroup.com/find-my-apartment/

    The first problem is that it is giving me a PHP error on this line:<?php foreach( $field['choices'] as $choice_value =>

    The second problem is, when I add ?bedrooms=3 or any other number to the URL it goes to a 404 page.

    The third thing I noticed – don’t know if this matters or not but when I add ?post_type=apartment to the URL it brings up the page just fine.

    So I really need some help getting this part at least functional. I also don’t really understand completely how this function interacts with the existing loop I have on the page. You can see below the PHP error I have a loop that displays out all the apartments with the custom fields. Do I need to do anything to change that loop for this to work?

    Thanks in advance!

  • Hi @megancm

    We can now agree that ACF is correctly loading the value, the problem you originally posted must be that you have a plugin that is modifying the pre_get_posts filter and preventing ACF from loading the gallery images.

    Perhaps you can start debugging in the relationship field file. There is a function for format_value_for_api` – this is where the posts are loaded in from the array of IDS.

    This will be a good place to start.

    Thanks
    E

Viewing 25 results - 301 through 325 (of 361 total)