How do you target a specific page in Wordpress functions.php? - wordpress

I am currently using the Multi Post Thumbnails plugin for Wordpress, but I only want the extra thumbnails provided by the plugin to show on one specific page. The plugin does not appear to natively support this functionality but it seems like something that would be pretty easy to add, I'm just not sure of the right way to go about it as I'm fairly new to Wordpress development.
The code for Multi Post Thumbnails is the following, which simply goes in functions.php:
if (class_exists('MultiPostThumbnails')) {
new MultiPostThumbnails(
array(
'label' => 'Secondary Image',
'id' => 'secondary-image',
'post_type' => 'page'
)
);
new MultiPostThumbnails(
array(
'label' => 'Tertiary Image',
'id' => 'tertiary-image',
'post_type' => 'page'
)
);
}
It seems to me it would just be a simple case of wrapping this in a check so that it only runs for a specific page ID, but I'm not quite sure how to go about doing that.

This is probably somewhat of a hack. To my knowledge post/page id's are not accessible from inside functions.php.
// get the id of the post/page based on the request uri.
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$post_id = url_to_postid($url);
// the id of the specific page/post.
$specific_post_id = 3;
// check if the requested post id is identical to the specific post id.
if ($post_id == $specific_post_id) {
if (class_exists('MultiPostThumbnails')) {
new MultiPostThumbnails(
array(
'label' => 'Secondary Image',
'id' => 'secondary-image',
'post_type' => 'page'
)
);
new MultiPostThumbnails(
array(
'label' => 'Tertiary Image',
'id' => 'tertiary-image',
'post_type' => 'page'
)
);
}
}

This is also probably a hack but it worked for me. I got stung by the AJAX 'post_id' back to the admin page once the image has been selected. My usage was for a slug but the function could easily be modified for a post ID.
function is_admin_edit_page( $slug ){
if( ( isset($_GET) && isset($_GET['post']) ) || ( isset($_POST) && isset($_POST['post_id']) ) )
{
$post_id = 0;
if(isset($_GET) && isset($_GET['post']))
{
$post_id = $_GET['post'];
}
else if(isset($_POST) && isset($_POST['post_id']))
{
$post_id = $_POST['post_id'];
}
if($post_id != 0)
{
$c_post = get_post($post_id);
if( $c_post->post_name == $slug )
{
return true;
}
}
}
return false;
}
if( is_admin_edit_page('work') ) {
new MultiPostThumbnails(
array(
'label' => 'Hero 1 (2048px x 756px JPEG)',
'id' => 'am-hero-1',
'post_type' => 'page'
)
);
}

Related

wp_localize_script is not accepting dynamic value

*Context
I am new to WordPress plugin development and I have just started developing one. Which is basically a blog slider plugin. The concept is very simple. The user can use shortcodes with parameters to determine which posts and how many posts to be shown. There is no admin settings page for changing the appearance of the slider though, but I'll work on that. The user have to use shortcode whenever the slider is needed.
The development part is also simple. I am checking the parameters that the user passes through the shortcode. And then a query runs and returns an array of posts and then displays the structure. Very simple.
*Problem
Now I am trying to make the plugin options more dynamic (via shortcode) i.e. the user can control whether the slider should auto-play or not, loop should be enabled or not, pause on hover, dots/nav hide or show etc. I am using owl carousel for this slider. So that means I have to change the attributes of the slider in JavaScript file.
The basic idea is to take the parameters from function's $atts array, and pass it to the JavaScript file. I know this can be accomplished using wp_localize_script, but I cannot figure out how.
Here is my code to make things more clear.
mainfile.php
add_shortcode( 'sp-slider', 'sp_slider_get_posts');
function sp_slider_get_posts( $atts ) {
$values = shortcode_atts( array(
'number' => '-1',
'category-id' => '', //DEFAULT VALUE null, WILL BE REPLACED ONCE USER DECLARES IN SHORTCODE
'category-name' => '',
'orderby' => '',
'order' => '',
'include-posts' => '',
'exclude-posts' => '',
'author-id' => '',
'author-name' => '',
'autoplay' => ''
), $atts );
if( !empty($values['number']) ||
!empty($values['category-id']) ||
!empty($values['category-name']) ||
!empty($values['orderby']) ||
!empty($values['order']) ||
!empty($values['include-posts']) ||
!empty($values['exclude-posts']) ||
!empty($values['author-id']) ||
!empty($values['author-name']) ||
!empty($values['autoplay'])) {
$args = array(
'numberposts' => $values['number'],
'cat' => $values['category-id'],
'category_name' => $values['category-name'],
'orderby' => $values['orderby'],
'order' => $values['order'],
'include' => $values['include-posts'],
'exclude' => $values['exclude-posts'],
'meta_key' => '',
'meta_value' => '',
'post_parent' => '',
'author' => $values['author-id'],
'author_name' => $values['author-name'],
'post_status' => 'publish',
'suppress_filters' => true,
'fields' => '',
);
$autoplay = $values['autoplay']; //GET AUTOPLAY VALUE. NO IDEA HOW TO USE IT. SO I TRIED THE FOLLOWING
// THE FOLLOWING FUNCTION HOLDS THE wp_localize_script FUNCTION, WHICH IS DECLARED AT THE END OF THIS CURRENT FUNCTION sp_slider_get_posts.
sp_carousel_settings($autoplay); //PASSING THE USER INPUT
$posts_array = get_posts( $args );
if( !empty( $posts_array ) ) {
$output = "<div class='sp-slider-wrapper'>";
$output .= '<div class="owl-carousel owl-theme">';
foreach( $posts_array as $post ) {
include( "includes/inc_slider_section.php"); // ALL THE SLIDER STRUCTURE IS IN DIFFERENT FILE WHICH IS INCLUDED HERE
}
$output .="</div>";
$output .="</div>";
}
return $output;
}
}
// HERE IS sp_carousel_settings() DECLARATION
function sp_carousel_settings( $autoplay ) {
$carousel_settings = array( 'autoplay' => $autoplay);
wp_localize_script( 'sp_main_js', 'carousel_settings', $carousel_settings );
}
add_action( 'wp_enqueue_scripts', 'sp_carousel_settings' );
mainjs.js
$(document).ready(function() {
...
...
var autoplay= '';
if(typeof carousel_settings !== 'undefined') {
autoplay = carousel_settings.autoplay;
}
else {
autoplay = false;
}
$('.owl-carousel').owlCarousel({
loop:true,
autoplay:autoplay,
autoplayTimeout:2000,
autoplayHoverPause:true,
...
...
}
})
This doesn't work. Here I would like to mention that, in add_action() function, if i put wp_footer instead of wp_enqueue_scripts, it adds the script to the footer of the page (I have checked it by viewing the source) but the autoplay value is null.
Another thing i would mention is that, in sp_carousel_settings() function, instead of passing the $autoplay variable, if I write any static value like this $carousel_settings = array( 'autoplay' => true);, it works.
*I tried echoing out $autoplay inside sp_carousel_settings() and it prints the value! But does not get to the js file.
*I tried checking the value of $autoplay and pass a hardcore sting inside wp_localize_script like
function sp_carousel_settings( $autoplay ) {
if( $autoplay == "true" ) {
echo "Inside!!!";
$carousel_settings = array( 'autoplay' => true);
}
else {
echo "Outside!!!";
$carousel_settings = array( 'autoplay' => false);
}
wp_localize_script( 'sp_main_js', 'carousel_settings', $carousel_settings );
}
add_action( 'wp_footer', 'sp_carousel_settings' );
Does not work. EVEN it prints out "Inside!!!" but does not pass true in autoplay. The value is always false.
*I have registered the js file in the beginning of the plugin, where the plugin activates and gets initialized. Like this
function sp_slider_include_css_js() {
...
...
wp_register_script('sp_main_js', plugins_url('assets/js/main.js',__FILE__));
wp_enqueue_script('sp_main_js');
...
...
}
add_action( 'wp_footer','sp_slider_include_css_js');
*I have searched internet for help but was unable to find. Any reference will be appreciated.
*I know that I might be using the function in an improper way. I am clueless (and new to this).
Have to do some changes like,
Step 1:
function sp_carousel_settings() {
wp_register_script( 'sp_main_js', 'you/file/path/here', array( 'jquery' ), '1.0', true);
}
add_action( 'wp_enqueue_scripts', 'sp_carousel_settings' );
Step 2:
add_shortcode( 'sp-slider', 'sp_slider_get_posts');
function sp_slider_get_posts( $atts ) {
.....
$carousel_settings = array( 'autoplay' => $autoplay);
wp_localize_script( 'sp_main_js', 'carousel_settings', $carousel_settings );
wp_enqueue_script( 'sp_main_js' );
......
}

ACF Dynamic select values not showing data

This question makes me crazy for almost 2 weeks. I know I am not expert in Wordpress, so I am seeking for help here.
I have create a href that when user click it will go to new page.
Add Class2
This href post the Post id. Url display:
[http://localhost/dev6/create-class/?post=289][1]
create-class page:
At create-class page,I am using GET method to display post id from url
$post = $_GET['post'];
I have acf form in create-class page for create new post. In this form, there have dynamic select field but the select field not display any data.
<?php acf_form(array(
'post_id' => 'new_post',
'field_groups' => array(150),
'post_title' => false,
'post_content' => false,
'new_post' => array(
'post_type' => 'classes',
'post_status' => 'publish',
),
'return' => '%post_url%',
'submit_value' => 'Submit',
//'updated_message' => 'Course Submit!',
)); ?>
in my function.php I create function for dynamic select:
function acf_load_t_first_name2_field_choices($field) {
global $post;
//$post = $_GET['post'];
// reset choices
$field['choices'] = array();
// get the textarea value from options page without any formatting
$choices = get_field('t_first_name',$post->ID);
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['choices'][ $choice ] = $choice;
}
}
// return the field
return $field;
}
add_filter('acf/load_field/name=t_first_name2', 'acf_load_t_first_name2_field_choices');
Is there something wrong with my code?
I don't believe this will work in your create-class template:
$post = $_GET['post'];
You will need to set something like this up in your functions.php file:
function custom_query_vars_filter($vars) {
$vars[] .= 'post';
return $vars;
}
add_filter( 'query_vars', 'custom_query_vars_filter' );
Then, in your create-class template you can get the variable from the URL like this:
$post = get_query_var('post');
See if that gets you going in the right direction.

Show Authors in a Page Based on Selected Metadata

I'm working on a new project where registered users can select multiple careers in the User Profile page in wordpress Admin. I have been able to add the check boxes of different careers to the User profile page which registered users can check/select.
At the frontend, I created a page for each of the careers. I want a scenerio whereby if one should go to page named "Programmer" for example, one would be shown all the authors that check "Programmer" in their profile. The authors info like avatar, name and links to all posts would be shown in a loop
I don't know how to go about it. Hoping you guys here can assist with this.
-------------------------------EDITED---------------------------
With the help provided by #AustinWinstanley thus far, here is my code
$user_query = new WP_User_Query( array( 'meta_key' => 'career', 'meta_value' => 'programmer' ) );
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
echo '<p>' . $user->display_name . '</p>';
}
} else {
echo 'No users found.';
}
With the above query, any author whose career field's value is programmer is listed. The above code is suitable if the value field for Career is an input field. I don't intend to make career's value to be an input field, rather I want it to be checkboxes where authors can check multiple values.
Since it's not going to be an input field, but rather checkboxes, how do I edit this line to reflect what I want?
$user_query = new WP_User_Query( array( 'meta_key' => 'career', 'meta_value' => 'programmer' ) );
You probably want to query users by meta data. Something like this:
// Set this value by whatever you're searching for
$career = 'programmer';
$args = array(
'meta_query' => array(
'relation' => 'AND',
array(
array(
'key' => 'career',
'value' => $career,
'compare' => 'LIKE'
// Or 'compare' => '='
)
)
)
);
$user_query = new WP_User_Query( $args );
$result = $wp_user_query->get_results();
Edit:
For the front end form:
<form method='post'>
<input name="careers[]" type="checkbox" value="programmer"> Programmer
<input name="careers[]" type="checkbox" value="accountant"> Accountant
<input name="careers[]" type="checkbox" value="manager"> Manager
<button name="career-search">Search</button>
</form>
In your plugin or function/includes:
function careers_postback( $query ) {
if( $query->is_main_query() && isset( $_POST['career-search'] ) ) {
$careers = $_POST['careers']
$meta_query = array();
foreach( $careers as $career ) {
$meta_query[] = array(
'relation' => 'AND',
array(
array(
'key' => 'career',
'value' => $career,
'compare' => '='
)
)
);
}
$args = array(
'meta_query' => $meta_query
);
$user_query = new WP_User_Query( $args );
$result = $wp_user_query->get_results();
set_query_var( 'search-career-results', $result );
// Here you would include your search template and call exit
// In your template, use `get_query_var( 'search-career-results')
// Then check if there are results and list them if there are.
}
}
add_filter( 'pre_get_posts', 'careers_postback' );
This is in general. I haven't fully tested it because I'm not typing it in an editor. But this is the full solution to check boxes and get users by their meta data using the data. If this doesn't work in general, then you are doing something you aren't revealing. Like not saving careers to user meta data.

Creating a page with wp_insert_post()

I have a form that collects data about a user's product and then creates a page in WordPress with
$my_post = array(
'post_content' => "My page content",
'post_title' => $product_title,
'post_name' => $product_title,
'post_type' => 'page', // must be 'page' to accept the 'page_template' below
'page_template' => "listing.php",
'post_status' => "publish"
);
$ID = wp_insert_post( $my_post );
$permalink = get_permalink($ID);
echo "<br />ID for new page is $ID, Permalink for new page is $permalink";
The form data is put into meta variables for the page ID and the listing.php template file pulls it out of there and builds the HTML to display the product page. This all works fine and I can see that the page meta variable, _wp_page_template, gets set correctly to the template file I specified, listing.php:
Now I want to create a second page from the same form data, this one displaying different parts of the data in a different way. So I've added a second block of code, starting at $my_cert below, that creates this second page and specifies a different template, certificate.php, that knows how to build the second version of the data.
$my_post = array(
'post_content' => "My page content",
'post_title' => $product_title,
'post_name' => $product_title,
'post_type' => 'page', // must be 'page' to accept the 'page_template' below
'page_template' => "listing.php",
'post_status' => "publish"
);
$ID = wp_insert_post( $my_post );
$permalink = get_permalink($ID);
echo "<br />ID for new page is $ID, Permalink for new page is $permalink";
$my_cert = array(
'post_content' => "My certificate", // post_content is required
'post_title' => "My certificate", // post_title is required
'post_name' => "My certificate",
'post_type' => 'page', // must be 'page' to accept the 'page_template' below
'page_template' => "certificate.php",
'post_status' => "publish"
);
$CERT_ID = wp_insert_post( $my_cert );
$cert_permalink = get_permalink($CERT_ID);
echo "<br />ID for new certificate is $CERT_ID, Permalink for new certificate is $cert_permalink";
But when I look in the meta data for the second page created, the template is set to "default" instead of certificate.php:
I know I've set up certificate.php correctly as a template (set /* Template Name: certificate */ at the top) because the Page Edit Template dropdown includes certificate:
So does anyone see why I can't create this second page with the template set to certificate.php?
Thanks
Are you sure your page template src for: certificate.php is: certificate.php? And not: templates/certificate.php or something like that. Look in your theme folder and be 100% of the page template path. Check your spelling or for typos in the page template path or name. It must be an exact match.
If you still have problems I would look into and debug the source code of: wp_insert_post()
if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
$post->page_template = $postarr['page_template'];
$page_templates = wp_get_theme()->get_page_templates( $post );
if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
if ( $wp_error ) {
return new WP_Error('invalid_page_template', __('The page template is invalid.'));
}
update_post_meta( $post_ID, '_wp_page_template', 'default' );
} else {
update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
}
}
So its probably this part that fails:
if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) )
Try to modify: wp-includes/post.php and go to the definition of: function wp_insert_post() on row: 2872. And add a new row on row: 3312 for debugging purposes.
echo '<pre>';
print_r( $page_templates );
echo '</pre>';
die();
Make sure your certificate.php is among those in that array. Remember to delete the debug code before continuing. This should give you some answers.

Does "Advanced Custom Fields" taxonomy field support user pages?

I have a "taxonomy" custom field for the user pages. I want to build a query filtered by this field. It works with normal querys but not with user-querys, am i doing something wrong?
<?php
$args = array(
'key' => 'fruits',
'value' => 'apple'
);
// The Query
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
echo $user->display_name;
}
} else {
echo 'No users found.';
}
?>
Try get_users instead:
$users = get_users(array(
'meta_key' => 'fruits',
'meta_value' => 'apple'
));
var_export($users);
Wordpress codex: get_users()
Edit:
After a bit of research it turns out that get_users() is only a wrapper for WP_user_query, so switching to this function will make no difference.
However... did you notice that in my answer (and vrajesh') we have substituted your key with meta_key, and value with meta_value ... They are definitely defined in the WP_User_Query class, so I would be surprised if they didn't have any meaning.
If by chance you are using your original $args (which I guess does not actually refer to fruits and apples), then that may well be the explanation you are getting nothing.
try this:
$args = array( 'meta_key' => 'fruits', 'meta_value' => 'apple','compare' => '=');
Use WP_Query instead of WP_User_Query. WP_User_Query is used to retrieve data from user and usermeta table. And according to my understanding your are retrieving data from posts and postmeta table.
Class Reference/WP User Query and
Class Reference/WP Query
UPDATED:
Try this
<?php
$args = array(
'meta_query' => array(
'key' => 'fruits',
'value' => 'apple',
'compare' => '='
)
);
// The Query
$user_query = new WP_User_Query( $args );
// User Loop
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user ) {
echo $user->display_name;
}
} else {
echo 'No users found.';
}
?>

Resources