INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
One comment per user email per post i have this code to limit the comments per user. <!-- #only one comment --> <?php global $current_user,$post; $args = array('user_id' => $current_user->ID,'post_id' => $post->ID); $usercomment = get_comments($args); if(count($usercomment) >= 1){ echo 'Thank you for your comment'; } else { comment_form(); } ?> My question is: how can edit this code to check for the author email rather than user id Thank you.
Try this, the code below will generate every comment by the `$current_user->user_email` for the author_email, if the `$usercomment` return something, then there is a comment by the current user so echo "thank you", but if it's not return anything output the form. global $current_user,$post; $usercomment = get_comments(array('author_email' => $current_user->user_email, 'post_id' => $post->ID)); if($usercomment) { echo "Thank You"; } else { comment_form(); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, comments, email" }
update_user_meta duplicates entry I have a very simple code in my themes footer if (is_user_logged_in()) { $user = wp_get_current_user(); $aka2 = get_user_meta($user->ID, 'last_visited_blogs', true); $aka2[] = 'blog4'; update_user_meta($user->ID, 'last_visited_blogs', $aka2); } ?> What it does is, gets meta value, inserts new entry and updates meta with new a array. like if it contain something: [0] => 'blog1', [1] => 'blog2', [2] => 'blog3' and after function it should look like [0] => 'blog1', [1] => 'blog2', [2] => 'blog3', [3] => 'blog4' but, what it does is, it inserts two values on execution even when it's empty [0] => 'blog4', [1] => 'blog4' and on every next execution it inserts two values
You are overwriting the existing values instead you should check if existing values exist and concatenate the new values to existing values if it is exist as following if (is_user_logged_in()) { $user = wp_get_current_user(); $aka2 = get_user_meta($user->ID, 'last_visited_blogs',true); if($aka2) array_push ($aka2, 'blog4'); else $aka2 = array('blog4'); update_user_meta($user->ID, 'last_visited_blogs', $aka2); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "array" }
Getting WordPress Flexslider Item Number I add flexslider to my theme home page via this code.how can I get number of per item? **as 1 2 3 4 ......** <?php $args = array( 'post_type' => 'try', 'posts_per_page' => 3 ); $query = new WP_Query( $args ); while ($query->have_posts()) : $query->the_post(); ?> <li class="featured-game"> <?php the_post_thumbnail('featured'); ?> <div class="caption"> <a href="#" class="game-title"><?php the_title();?></a> <?php the_excerpt(); ?> <a href="#" class="playnow">Play Now</a> </div> </li> <?php endwhile; ?> </ul>
You can use $item_nr = $query->current_post; to give you the position within the loop (starts from `0`). If you need the first item to start with `1`, you can use: $item_nr = $query->current_post; $item_nr++; Total number of posts found: $items_found = $query->found_posts;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types" }
Why does the page/post ID keep growing when i refresh the post-new.php file? I created a custom post type and for debugging reasons i display the Post ID on the Add New ... page. If i refresh the page without saving or even creating a new post,(so i just press f5 on the post-new.php) the post ID is growing one by one. Why is this happening and is this the normal behaviour?
This is normal behaviour, as I understand it. When you load the page `post-new.php`, you run this function: $post = get_default_post_to_edit( $post_type, true ); where the second argument stands for `$create_in_db`. If true then this part is executed: if ( $create_in_db ) { $post_id = wp_insert_post(...); } inside `get_default_post_to_edit()`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "id" }
How to remove Gravatar from Username column How to remove the **Gravatar** image from **Username column** in the **All User** admin page? !enter image description here
There seems to be a **filter** for the `get_avatar` function. So I just output an empty string to it. function remove_avatar_from_users_list( $avatar ) { if (is_admin()) { global $current_screen; if ( $current_screen->base == 'users' ) { $avatar = ''; } } return $avatar; } add_filter( 'get_avatar', 'remove_avatar_from_users_list' ); **UPDATE:** Restrict to ' **All Users** ' page only.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "admin, users, columns, screen columns" }
How to set thumbnail image for a (child) theme I've created a basic child image for twentytwelve, and it works as expected. The only issue is that it does not have a thumbnail image in the themes page: !enter image description here How do I set a thumbnail image for my child theme?
Create image file in PNG Format having name screenshot.png and save it in themes root folder.The recommended image size is 880x660. Even recommended image size is 880x660 though it will only be shown as 387x290 but the double-sized image allows for high-resolution viewing on HiDPI displays. For more information see this page. If you don’t already have a screenshot of your theme, You can create one easily by following below steps: 1. Point your browser to the blog currently using the theme. 2. Press the Print Screen button on the keyboard. 3. Open a new file in Photoshop. 4. Change the size to 300 by 225 (in pixels) 5. Press Ctrl + v or Right click > Paste. 6. With the Move tool activated, resize the screenshot to in the 600 x 450 space. 7. Go to File > Save for Web… 8. Save it as a PNG file. 9. Name it screenshot such as screenshot.png 10. Place your image file in the theme’s folder.
stackexchange-wordpress
{ "answer_score": 16, "question_score": 9, "tags": "themes, child theme, thumbnails" }
Insert custom fields to a custom post type I am creating a small blog about my trekking and camping experience. Since different experiences - like campsites, treks and tour operators - have different metadata, I have created a custom post types (e.g. `campsite`), associated with custom field types (e.g. `price`, `water_supply`). Now I'm trying to use these fields in my child theme. I've copied twenty-twelve - the parent - `single.php` to `single-campsite.php`, and started digging in. The problem is that the entire post content - title, content, and date - is created from this single line: <?php get_template_part( 'content', get_post_format() ); ?> **How do I edit the post internals, e.g. insert custom fields between the title and the contents, or remove the date below?**
That statement grabs a file called content-post-format.php in the theme directory, depending on the post format. Posts will grab content.php since there is no post format. Copy the information out of content.php into single-campsite.php and go from there. Alternatively, you can create a copy of content.php called content-campsite.php and call: <?php get_template_part( 'content', 'campsite' ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom field, child theme" }
Store SNS share value via function.php I am trying to store SNS share value + comment count on my postmeta, DB. I put code below to accomplish this task, function get_sns_share($post_ID=0) { $url1=get_permalink($post->ID); $src = json_decode(file_get_contents(' . $url1)); $share_count = $src->shares; // facebook commnet + comment like + share + like $my_var = get_comments_number( $post_id ); // comment count $social_score = $share_count + $my_var + $tweet; // social score sum if ($social_score > 999) $social_socre = 999; return $social_score; update_post_meta($post_id, '_social_score', $social_score); } The problem is this code certainly do works every field other than update_post_meta. It seems it does not add add post meta field to my database, thus I cannot get any value from there. Your help would be much appreciated.
Within a function or method, the `return` statement immediately stops the execution of the earlier. Hence the last line never gets interpreted. Switch the order of this: return $social_score; update_post_meta($post_id, '_social_score', $social_score); to this: update_post_meta($post_id, '_social_score', $social_score); return $social_score; **Update:** You are using three different variables for the post id, namely: `$post_ID`, `$post_id` and `$post->ID`. You should use the function argument: `$post_ID`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "facebook, post meta, social sharing" }
Get custom field label I've defined some custom fields using Advanced Custom Fields, and I display these fields as keys and values using `get_post_meta`, e.g.: <span class="campsite_meta_key">מחיר:</span> <?php echo get_post_meta($post->ID, 'price', true);?> , <span class="campsite_meta_key">מפה:</span> <?php echo get_post_meta($post->ID, 'map', true);?> ... This involves code duplication, because the Hebrew name of the field (e.g. `מפה`) is already defined as the custom field _label_. **Is there a way to programmatically retrieve the a custom field label?**
See the ACF documentation for `get_field_object`: $field_object = get_field_object( 'price', $post->ID ); echo $field_object['label'];
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom field" }
WooCommerce: List All Categories I'm using the WooCommerce plugin with WordPress and within my theme I'd like to list all categories within a navigation menu with PHP. I've tried using `woocommerce_product_categories();` but I don't want the images, or other HTML elements, just their names (and maybe permalinks). How can I get that data?
taken from that very same function: // prior to wordpress 4.5.0 $args = array( 'number' => $number, 'orderby' => $orderby, 'order' => $order, 'hide_empty' => $hide_empty, 'include' => $ids ); $product_categories = get_terms( 'product_cat', $args ); // since wordpress 4.5.0 $args = array( 'taxonomy' => "product_cat", 'number' => $number, 'orderby' => $orderby, 'order' => $order, 'hide_empty' => $hide_empty, 'include' => $ids ); $product_categories = get_terms($args); will give you the list of product categories. easy!
stackexchange-wordpress
{ "answer_score": 29, "question_score": 11, "tags": "categories, plugins" }
What do the numbers mean at the end of add_action('save_post')...? I've seen on a few tutorials that there are numbers at the end of the call to save Custom Fields/Meta Boxes on the `save_post` hook. For example, in the WordPress Codex it gives the following example: <?php add_action( 'save_post', 'my_save_post', 10, 2 ); ?> What do the **10** and **2** mean at the end? I've tried talking to an "expert", but they've been of no help ;)
The 10 is the priority (relative to other added actions) and the 2 is simply the number of arguments that my_save_post() will accept. See the codex.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom field, metabox, actions, save post" }
Multiple custom fields with the same name Is it possible to have several custom fields with the same name? For example, I have a custom field called "promotion" for a CPT called "event". Sometimes there are more than one promotion applied to the same event, each for a certain type of participant. So I'd like to have one "promotion" custom field with a value "X, A" and another "promotion" custom field with a value "Y, B". I tried to create this then retrieve it with `get_post_meta()` and display the result with `print_r()`, but all I get is one of the values only ("X, A"). Here's the code: $event_promotion = get_post_meta($post->ID, "Event Promotion", true); print_r($event_promotion); Perhaps it's just not possible to proceed this way?
Yes, it's possible to have multiple fields with the same key. When using `get_post_meta($post_id, $key, $single)`, make sure you set the `$single` parameter to `false` (or just leave it off since it defaults to `false`). get_post_meta( $post->ID, 'Event Promotion', false ) or get_post_meta( $post->ID, 'Event Promotion' ) This will return an array containing every value of the key (what you're expecting). If you set `$single` to `true` it will return the first value of the specified key as a string (what you're currently getting). References: < <
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "custom field" }
Is there a WordPress boolean for "theme_customizer_active()"? Looking to add an action to `wp_head` but only if the user is in "theme customizer" mode. Does anyone know if there's a conditional for this?
Hook a function to the `customize_preview_init` action. In that function, do your add_action for the `wp_head`. The `customize_preview_init` action runs in the call that renders the frame that the preview page is displayed on, and happens early enough to hook onto wp_head.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, customization, theme customizer" }
Difference Between Admin and Super Admin in Database I was looking at the user table and noticed for a super admin ( have access to network admin panel ) and an admin to a network site have same `wp_capabilities` which is `a:1:{s:13:"administrator";b:1;}` and also the `wp_user_level` is `10` for both. So, I was wondering **what is the database value that differentiate between a super admin and an admin?** I don't see any more usermeta that relates to network admin level. What is the proper way to assign super admin capability to a admin via: 1. Database Edit. 2. Via Code.
Site admins are stored in a site option as an array of usernames. For example, using SQL in MySQLWorkbench you can do a query such as this: SELECT * FROM wp_sitemeta where meta_key='site_admins'; To get back a serialised PHP array. Modifying this value by adding your username and user ID will make you a site admin. If you're just looking to see who is a site admin, you have these functions: get_site_admins(); is_super_admin(); If on a single site rather than a multisite, any user with the delete_users capability will be regarded as a super admin.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "multisite, wp admin" }
Can I use add_option for a plugin categories and how? So I am creating my first plugin for positioning ads around my site. I created one separate table where I store ads with all their options, such as position, expire date, active, name, type etc... But Now I need just one field where I can allow users to create categories for these ads, add new, delete existing categories etc, so an array of data... I am looking at add_options and update_options ,can I use this options API for array ? For example, I have a form where user can add new categories, but if I use update_options, I suppose that I will just replace latest added category, instead adding it to an array ? Shall I extract current data, add this one and update it ? I am also relative new with PHP but expert in front end. I know that I can do it easly with new table, but I am trying to use WP built in stuffs as much as possible.
Create the ads as custom post types and register one or more custom taxonomies for these post types. You can set up the other meta data as post meta (also known as custom fields). The options table is probably not the best place for these data; because you have to reinvent the wheel.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "settings api, options" }
single-mySlug.php works: archive-mySlug.php does not. Custom Post Type I am registering a custom post type (listing) with a plugin and it has two taxonomies. It all seems to work as expected. I can display individual posts from the CPT using `single-listing.php` but I can't display a full page using `archive-listing.php`. I just tried `taxonomy-organisation.php` which is the CPT taxonomy and this works too. I am using a child theme and just used a copy of the parent archive/siingle/taxonomy pages This is a copy of WP 2012 theme file which I named `archive-listing.php`: < This is my CPT plugin: < This URL uses the archive.php file in the parent theme: <
Your setup would mean that archive-listing.php would be used at: < However, your URL: < Is not a post archive, it's a taxonomy archive, specifically an organisation archive, and so `archive-listing.php` will never be used for it, since archive-listing is not a taxonomy archive template but a post archive template. Other than doing an include in `taxonomy-organisation.php` there is no way to make it call `archive-listing.php`, except for messing around with hooks and filters, which I strongly recommend against as it would be a waste of time and effort ( why not just include ). I recommend looking up the template hierarchy diagram and bookmarking it
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom post type archives" }
Why do I get email notifications about comments that Wordpress has already determined are spam? I have a wordpress.org blog that I host on my own site. I have the Akismet plugin installed, and in general I keep both up-to-date (e.g. at the moment, Akismet is at version 2.5.7, and Wordpress at 3.5.1). From time-to-time (maybe every week or so), I get a notification email from Wordpress that a (generally spam) comment needs moderating. When I log in to moderate it, Wordpress informs me that it has already been marked as spam (although I haven't marked it so, but I assume Wordpress means that Akismet has determined that). In this case, why do I get the notification email in the first place? Is Akismet failing to connect to the Akismet service, notifying me, and retrying later? If so, is it possible to turn off the initial notification email in this case? It's irritating to log in to moderate something only to discover Wordpress already knows the answer!
Disclaimer: I wrote parts of the Akismet WordPress plugin, though not the parts in question here. > Is Akismet failing to connect to the Akismet service, notifying me, and retrying later? Yes, this is exactly what happens. If Akismet doesn't get a valid response from the servers, it reschedules the check for 20 minutes in the future. In the meantime the post is considered held for moderation, since its actual status (ham or spam) is yet undetermined. > If so, is it possible to turn off the initial notification email in this case? I regret that I don't know of any good way to do this for _only_ this circumstance. But I have never had so much spam making it as far as Akismet that this happens more than once or twice a week, so I've never been bothered to make the attempt.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "comments, spam, akismet" }
Odd/even class on article tag I am using the article tag with the following code: <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix span4 '); ?> role="article"> </article> and I would like to add "odd" and "even" to the current `post_class`. I found the following code on other site: <?php echo (++$j % 2 == 0) ? 'evenpost' : 'oddpost'; ?> Why it isn't working with my code? <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix span4 <?php echo (++$j % 2 == 0) ? 'evenpost' : 'oddpost'; ?>'); ?> role="article">
Try this (untested): <?php $zebra = (++$j % 2 == 0) ? 'evenpost' : 'oddpost'; ?> <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix span4 ' . $zebra); ?> role="article"> You just need to place theodd/even class into a variable before passing it to post_class.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "posts, post class" }
Integrating CSS Into a WP Function Call Below is a code I use to display post views. It is integrated with an options panel which allows users to choose whether to display it. I would like to integrate the div class .postviews directly into the code. I would like to do this because it incorporates a blue background and if the views are not displayed, that blue background still gets displayed. <div class="postviews"> <?php $options = get_option('to_post_views'); if( $options == 'Yes' ) { echo getPostViews( get_the_ID() ); } ?> </div> If you view this page, views are currently being displayed where it says "58 views."
Apart from the fact, that the conditional is based on a WordPress option, this is pure PHP, but anyhoo: <?php $show_views = get_option( 'to_post_views' ); if ( 'Yes' === $show_views ) { echo '<div class="postviews">' . getPostViews( get_the_ID() ) . '</div>'; } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "php, functions, css, options, views" }
Show posts in a list separated by day I want to display posts on index page within a links-list, with only the titles, till now i did the job, but now i want to have space between titles and be separated by day. Please check wimp.com and see how the titles are separated. Right now my code is something like this <?php query_posts($query_string.'&cat=-3'); while (have_posts()) : the_post(); ?> <span class="date"><?php the_time('M j') ?></span> - <a class="title" href="<?php the_permalink() ?>"><?php the_title(); ?></a> Thanks.
Add a variable to hold the previous post's date, and then add a `<br />` or something when it changes. <?php $prev_date = ''; // initialize to empty string query_posts($query_string.'&cat=-3'); while (have_posts()) : the_post(); ?> <?php if( strlen( $prev_date ) > 0 && get_the_time( 'M j' ) != $prev_date ): ?> <br /> <!-- or whatever you want to use to separate your date blocks --> <?php endif; ?> <span class="date"><?php the_time('M j') ?></span> - <a class="title" href="<?php the_permalink() ?>"><?php the_title(); ?></a> <?php $prev_date = get_the_time( 'M j' ); ?> <!-- continue on with The Loop --> <?php endwhile; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "get posts" }
How to change the name of the "edit my profile" link in the WordPress admin backend I am really confused at this point. I can not figure it out how to rename `Edit My Profile` link in the admin backend. How can that be done?
You could use the `wp_before_admin_bar_render` hook. You can play with code samples on the Codex page by putting them in your theme's `functions.php`. First off you can try examining the object by outputting its contents with `print_r()`, and you'll see all the familiar items. I would probably use `remove_menu` helper and then add a new one with the modified link title, just to keep things clean. add_action( 'wp_before_admin_bar_render', 'my_tweaked_admin_bar' ); function my_tweaked_admin_bar() { global $wp_admin_bar; $wp_admin_bar->remove_menu('edit-profile'); $wp_admin_bar->add_menu( array( 'id' => 'edit-profile', 'title' => 'Edit Zee Profile', 'href' => admin_url('profile.php'), 'parent'=>'user-actions' )); } The downside of this approach is that the new item will not show up in the same spot.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, plugin development, admin, filters" }
Plugin: How should I handle deleting comments? I am writing a plugin that creates an api for a custom post type. Users can comments on the custom post types and the comments are added using WP core comment methods. My question arises when trying to deal with what to do when deleting a comment. I understand what methods to use, but my question is more about the general procedure. When you make a comment it can be a reply to another comment. If the parent commenter decides to delete their comment, what should be done with replies? Should they be deleted as well? Should their parent pointer just move one up the tree? You could also replace the deleted comment content with a message like, 'Comment deleted'. Like a placeholder. Then the replies could keep the same parent pointer, but they would lose the context of the original parent comment's content. Am I overthinking this?
Do not delete the comment. One comment could have multiple children, and moving the replies up would create a false impression in any case. The real question here is **why** someone wants to delete a comment and how you could react: * The content is obsolete or wrong: Add a note, mark it as outdated. * The commenter disclosed something _secret_ : Replace the comment content with a note. * The commenter doesn't want to be seen on the site anymore: replace the commenter name with _anonymous_. In any case, I would require a reason for deletion request, and create a separate comment review queue. Use comment meta fields for that.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugins, plugin development, comments" }
Auto close (hide) custom metabox / set default state I am using the WordPress function `add_meta_box()` to add my own custom metabox. So how can I auto close/hide on page open ? Currently, I just add a CSS class `closed` to metabox's `<div>` element via jQuery like so: **HTML :** (example) <div id="my_metabox" class="postbox"></div> **jQuery :** $("#my_metabox.postbox").addClass("closed"); But is there a WordPress function to do this ?
Hook into `postbox_classes`. `postbox_classes` is the function which will output the classes for the metabox. apply_filters( "postbox_classes_{$page}_{$id}", $classes ) Your code could look like this: add_action( 'add_meta_boxes', 'add_my_metabox' ); function add_my_metabox() { $id = 'my-metabox'; $title = 'My Metabox'; $callback = 'my_metabox_content'; $page = 'post'; add_meta_box( $id, $title, $callback, $page ); add_filter( "postbox_classes_{$page}_{$id}", 'minify_my_metabox' ); } function my_metabox_content() { ... } /* * $classes is an array */ function minify_my_metabox( $classes ) { if ( isset( $_POST['my_condition'] ) && 'my_condition' == $_POST['my_condition'] ) { array_push( $classes, 'closed' ); } return $classes; }
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "functions, metabox" }
get_avatar won't show uploaded avatar, only default gravatar I'm using the Simple Local Avatars plugin so my bbPress forumgoers can upload their own avatars. Now, when a user logs in, I want his/her avatar to display next to the relevant links (i.e. logout, edit profile, etc.). I tried the call below but it only keeps showing the default mystery man gravatar. `<?php echo get_avatar( $current_user->user_login, 48 ); ?>` Is there something I overlooked? How can I get the user's uploaded avatar to show up?
And of course as soon as I post the question, I find the answer. _slaps forehead_ <?php global $current_user; get_currentuserinfo(); echo get_avatar( $current_user->ID, 48 ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, avatar, gravatar" }
Correct syntax for retrieving custom field in CPT I don't understand when to use $post->ID or $post->post->ID with CPTs. I have : $event = get_post( $event_id ); $event_pre_register = get_post_meta($event->post->ID, "Event Pre-register deadline", true); Or is it : get_post_meta($event->ID ... ?
If you have the CPT's ID in the `$event_id` variable you plug into the `get_post()` call - why would you not simply just (re)use that for the first parameter of `get_post_meta()` ? That aside, `get_post()` returns a post object (instance of WP_Post), which you choose to assign to `$event`. Hence `$event` now has a public property `$ID`, which can be accessed by `$event->ID`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field" }
get_user_meta() doesn't include user email? I simply wonder why `<?php var_dump(get_user_meta(4)); ?>` doesn't contain an email address of the user. Instead I have to use `get_userdata(4)->user_email;` to query the email of the user. Why is that or did I miss something? `get_user_meta()` seems to provide all other aspects and informations of a user, however just not the email-address. Matt
`get_user_meta` retrieves a single meta field or all fields of the `user_meta` data for the given user. This means that all the values that are stored in `user_meta` table can be got using `get_user_meta`. Email is not stored as meta data so you cant get email using `get_user_meta`. Email is stored with username and password in `user` table as user data.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 10, "tags": "users, email, user meta" }
How to display product categories and number of sales on WooCommerce I am currently working on a WooCommerce site.I managed to set it up,do some configuration according to my plan.Now i want to display product categories alongside each products in product catalog,and also want to display how many time the product has been sold too. I have done some searching and found this code,which displays product categories,but i want to display category with link to it. <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); $parents = get_the_terms($term->parent, get_query_var('taxonomy') ); echo "<div class='product-cat'>"; echo "In"." "." "; foreach( $parents as $parent ) { echo $parent->name; } ?> Please help out on this.Thanks in advance.
Try looking in the Codex for answers. You will find that `get_term_link()` creates links to terms. foreach( $parents as $parent ) { echo get_term_link( $parent ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, plugins" }
Why do some pages on my site use the previous theme? I have developed a WordPress website using a Child Theme, I started with Twenty Ten as the base, then I created a new and improved version with Twenty Eleven as the base and some new features, now I have done it again with Twenty Twelve as the Parent theme. The new features are working mostly great, except when viewing certain pages on the site it wants load the Stylesheet, etc. from the previous (Differently named, Twenty Eleven child) theme. Why? URL: < Observe the home page (header, menu, sidebar, etc), then click on the "CLASSES" or "FIND WINE" link to see what I am talking about. Thank You
During development disable all caching. Short check list: * no caching plugins active * no caching rules in .htaccess * add a time stamp to your theme stylesheets * add a time stamp to editor stylesheets
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "page template, child theme" }
Retrieve a specific post's featured image and show on a different page What I'm simply trying to do is grab the featured image thumbnail image from a specified post/page and display that image on any other page somewhere. So for instance, if it's a single post, use the thumbnail from post 9. If it's this page, use the thumbnail from 82, and so on. It doesn't seem as simple as this: $thumbnail_id = get_the_post_thumbnail(82); Because I've tried that and it doesn't work in all scenarios. Is there a universal way to do this?
Looks like this might be the reason why it wasn't working the way I needed. before -> if ( has_post_thumbnail () ) Seems that only relates to the specific post/page you're on, and not the page/page that you're getting the image from - if you don't enter a post ID. But then I tried it with the post ID I was trying to retrieve from and it works. after -> if ( has_post_thumbnail (9) )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, post thumbnails" }
how do you point 'screen_function' to a function in the same class? In a plugin class, I'm successfully creating a new tab on a Member page using: bp_core_new_nav_item( array( 'name' => __( 'MyTab', 'bp' ), 'slug' => 'mytab', 'position' => 200, 'screen_function' => array( $this, 'mytab_screen' ), 'default_subnav_slug' => 'mytab' ) ); The problem appears when you click the tab. The function is found - this Warning _DOES NOT_ appear: Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback etc But the function is not called and you end up on the 'It seems we can’t find what you’re looking for.' page. Am I using the correct approach to point 'screen_function' to a public function in the same class ?
That is the correct approach. The problem was in the function mytab_screen() I wasn't using 'array' for the 2nd parameter in the add_action for the template call. Nothing fancy, just sloppiness.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, buddypress, profiles" }
shortcode change variable base on user How would I put this together. For plugin Contact Form 7 Data Base how would I add in the "Submitted Login" (user display name) to the search="name" Original Shortcode [cfdb-table form="Contact form 1" show="Submitted Login,your-email,your-message" search="AndrewA"] Tried to put this together a few ways, none worked. <?php echo do_shortcode('[cfdb-table form="Contact form 1" show="Submitted Login,your-email,your-message" search="' . $current_user->display_name .'"]');?> This is so users can see their contact form data they have submitted. Thanks for any help.
If this works for you in the template: $s='[cfdb-table form="Contact form 1" show="Submitted Login,your-email,your-message" search="AndrewA"]'; echo do_shortcode($s); then you could try: global $current_user; get_currentuserinfo(); $s = sprintf('[cfdb-table form="Contact form 1" show="Submitted Login,your-email,your-message" search="%s"]',$current_user->display_name); echo do_shortcode($s);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
How to get the post of category I have created the 2 categories. And these two categories have child category, how can i get the post of the category when I clicked on the category title. Please guide me
<?php // Get the ID of a given category $category_id = get_cat_ID( 'Category Name' ); // Get the URL of this category $category_link = get_category_link( $category_id ); ?> <!-- Print a link to this category --> <a href="<?php echo esc_url( $category_link ); ?>" title="Category Name">Category Name</a> After you click on the Category Title link, it will take you to the page where it displays all the posts under that category. Note: category.php, archive.php template files are responsible for the display, else index.php will be used.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
How to add the sidebar in all category page I created custom post type. I created category called product-categories. I listed all categories in sidebar.php. How to show the sidebar in all the category pages listing all the categories. Sidebar.php code is, 'name', 'order' => 'ASC', 'hide_empty' => 0, 'use_desc_for_title' => 1, 'child_of' => 21, 'hierarchical' => 1, 'number' => null, 'echo' => 1, 'taxonomy' => 'product-categories', 'walker' => null, 'title_li' =>'' ); ?> I want to display this code visible in all the category pages. Please guide me
the following code will work as for per your custom post type add the following code in sidebar.php to show your custom post type category <?php //list terms in a given taxonomy using wp_list_categories (also useful as a widget) $orderby = 'name'; $show_count = 0; // 1 for yes, 0 for no $pad_counts = 0; // 1 for yes, 0 for no $hierarchical = 1; // 1 for yes, 0 for no $taxonomy = 'genre'; $title = ''; $args = array( 'orderby' => $orderby, 'show_count' => $show_count, 'pad_counts' => $pad_counts, 'hierarchical' => $hierarchical, 'taxonomy' => $taxonomy, 'title_li' => $title ); ?> <ul> <?php wp_list_categories($args); ?> </ul>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, sidebar" }
wp_dropdown_categories initial value I am currently pulling in an option drop-down of a specific category using: <?php wp_dropdown_categories('child_of=20'); ?> I would like the initial value of the drop-down to say 'Bedrooms' and not be the first category. Is this possible?
you can set the initial value of categories drop down by passing category id to selected parameter of wp_dropdown_categories function as shown in following code : wp_dropdown_categories( array( 'child_of' => 20, 'selected' => get_cat_ID( 'Bedrooms' ) ) ); For more information on this visit this code page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, options, dropdown" }
How to i18n slugs for templates? some templates are chosen from WordPress based on slugs (e.g. `category-{slug}.php`). Problem: How can I use the same template for an i18n'ed slug? Example: I have a `category-news.php` and an english category with slug "news" and german category with slug "nachrichten". But of course "nachrichten" doesn't get `category-news.php` as a template. How can I i18n "nachrichten" so WordPress knows it means "news" before the template will be chosen internally?
Filter `template_include`: add_filter( 'template_include', 'prefix_translate_template' ); function prefix_translate_template( $template ) { if ( 'category-' . __( 'news', 'your_textdomain' ) . '.php' === $template ) return 'category-news.php'; return $template; } But I think templates based on slugs are not a good idea in that case.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "permalinks, slug, localization" }
How to add a div around the default gallery output I would like to add a container around the default [gallery] output. I don't want to modify any core files, and add unusual lines to my functions.php. How to do that? What's the most elegant method?
Well, since you don't want to edit core files (which is absolutely fine, and unnecessary) and also don't want to do it by means of PHP (meaning `functions.php`, for instance), here's a jQuery approach: $('div[id^="galleryid-"]').wrap('<div id="SOME_ID" class="SOME_CLASS" />'); BTW, you know there already is a container `div` that you can hijack for CSS purposes, right?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "gallery" }
Show activities of defined BuddyPress groups I want to show activity loop for certain groups only. If I use <?php if ( bp_has_activities( array(bp_ajax_querystring( 'activity' ),'object' => 'groups','per_page'=>6 ,'primary_id' => $group_id, 'page' => isset($_REQUEST['page']) ? $_REQUEST['page'] : 1 ) ) ) : ?> I can pass one group ID to filter results. The problem is that I have an array of groups IDs. I tried <?php if ( bp_has_activities( array(bp_ajax_querystring( 'activity' ),'object' => 'groups','per_page'=>6 ,'in' => $groups_ids, 'page' => isset($_REQUEST['page']) ? $_REQUEST['page'] : 1 ) ) ) : ?> But `'in' => $array` only takes an array of activities IDs. How to achieve this?
After getting all the groups_ids i get all activities_ids by doing: <?php global $bp,$wpdb; $groups_ids = implode(', ', $groups_ids); $sql = "SELECT id FROM {$bp->activity->table_name} WHERE component = 'groups' AND item_id IN ({$groups_ids})"; $activity_ids = $wpdb->get_results( $sql); $a_id = array(); foreach ($activity_ids as $activity_id ) { $a_id[] = $activity_id->id; } ?> Then i get only one activity loop with the specified groups by doing: $params = array('per_page' => '6', 'in' => $a_id); if ( bp_has_activities($params) ) : endif;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "buddypress" }
Hook or function to upload media via url I am working on image aggregation site. Is there a wordpress hook or function to upload media especially image if a url is provided to it? Rest I can do with wp_handle_upload function. Thanks
See `media_handle_sideload` in Codex: $url = " $tmp = download_url( $url ); $post_id = 1; $desc = "The WordPress Logo"; // Set variables for storage // fix file filename for query strings preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $file, $matches); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if ( is_wp_error( $tmp ) ) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $id = media_handle_sideload( $file_array, $post_id, $desc ); // If error storing permanently, unlink if ( is_wp_error($id) ) { @unlink($file_array['tmp_name']); return $id; } $src = wp_get_attachment_url( $id );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "uploads" }
Is it safe to assume that a nonce may be validated more than once? From what I have gathered, once a nonce is generated it is valid for reuse for the next 48 hours. Is it safe to code with this in mind? I'm writing a plugin that does a bit of toing and froing with the client via AJAX and want to know if I should just generate a nonce when the page loads and use that for all communication or generate a new one for every request and include it in the response.
1, the nonce lifetime is about 24 hours by default actually. take a look at wp_verify_nonce function. To be more accurate, the lifetime is controlled by filter apply_filters( 'nonce_life', DAY_IN_SECONDS ); 2, if the lifetime value makes you doubt if it is "an implementation side-effect", you may want to `add_filter('nonce_life',create_function('$v', 'return 60*5;'));` to shorten the lifetime to 5 minutes in my example. 3, if you're concerned about the security of your plugin, you should use csrf token instead.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "ajax, security, nonce" }
Filter orders by product in admin I'm setting up Woocommerce store for a client who is selling tickets to multiple different live shows. On the night of a show, the box office manager needs to be able to view only orders that contain one specific product (the show). Does anyone know of a plugin that would allow a store manager to either view all orders that contain a specific product, or download a csv of those orders (ideally both)? Barring that, if anyone has had to do something similar and has any insights on adding custom filters to the order screen, I would really appreciate your input! Thank you.
You can simply use the "Search Orders" box on the top right, just enter the product name. Exporting those to csv requires a more tailored approach, not sure if Order/Customer CSV export is up to it (ask WooThemes and they'll be quick to respond)
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins" }
preg_match() not working with post content I'm new to Wordpress, and I wrote the following function: function find_my_image() { if(is_single()) { if (preg_match('#(<img.*?>)#', $content, $result)){ $content .= '<p>Image has been found</p>'; } else{ $content .= '<p>Sorry, no image here!</p>'; } } echo $content; } add_filter('the_content', 'find_my_image'); Basically, I just want to find out if my post has a image in it and display proper message. Currently, I'm always getting the false result, so I'm just wondering what am I doing wrong.
In your code, $content does not exist. You need to accept the argument into your function: function find_my_image( $content ) { if ( is_single() ) { if ( preg_match( '/(<img[^>]+>)/i', $content, $result ) ) { $content .= '<p>Image has been found</p>'; } else { $content .= '<p>Sorry, no image here!</p>'; } } return $content; } add_filter( 'the_content', 'find_my_image' ); Also, note that you should always return the content after your filter - see the codex.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters" }
In Settings>>General I am missing some fields I am new to Wordpress and downloaded the 3.5.1 version from my hosting provider. I want to add www in front of my domain and I read from many sources how to do this. Go to settings then general and change it there. Thats fine except my screen in General looks nothing like the instructions I have been following It does not have a place to change the Site or Wordpress URL. Am I missing something !enter image description here
You are in the wrong settings page. Your site is a multi-site setup; the URL is set in the site manager, not in individual sites. Go to **Network Admin/Sites** in the **My Sites** menu: !enter image description here Select a site to edit: !enter image description here Change the URL: !enter image description here ### Update You need a subdomain setup to get editable URLs. See Create A Network for the installation guide and Configuring Wildcard Subdomains for the server setup.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "urls, options" }
How to check if current static page is frontpage from admin plugin I set static page as front page. I need to know if user currently on homepage in my custom plugin. Functions **is_home()** and **is_front_page()** doesn't works, since homepage is static page. I can get an id of this page : $frontpage_id = get_option('page_on_front'); But how to get id of current page from admin plugin? (Then i'll be able to compare those ids and detect if current page is homepage!) 2 vancoder Code: 1) Set any static page as frontpage. 2) Create dummy plugin 3) Code of plugin : $d = is_front_page(); var_dump($d); ==> bool(false) **UPD** < should work, by didn't 2 Vancoder Admin plugin means just plugin :) sorry And those two lines is all context for now, try it yourself, it doesn't works. WP version 3.3.2
This is why I asked for more code context. I'll have to guess that you are checking for the front page outside of any hooked function, or inside a function that is called too early, before is_front_page() is ready. The following will work. function your_function() { $d = is_front_page(); var_dump($d); } add_action( 'wp', 'your_function' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin development, frontpage, homepage" }
How To Disable Comments On New Page I am writing a plugin that upon activation, it creates a few new pages. On these pages, I want to disable the comments option. I am adding the new pages via the code below: $page['post_type'] = 'page'; $page['post_status'] = 'publish'; $page['post_author'] = 1; $page['post_parent'] = 0; $page['post_title'] = 'Test Page'; $page['post_content'] = 'this is a test. i want to disable the discussion option.'; $pageid = wp_insert_post($page); In the WordPress codex, I do not see any option/property/meta to disable the Discussion section of a page/post. Does anyone know how?
As per the documentation: $page['comment_status'] = 'closed'; // allowed values: 'closed' or 'open'
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "comments, wp insert post" }
Send mail to wordpress admin I have a page on my wordpress site that has some fields to be filled by visitor. On the click event of 'submit' button, all the details filled by visitor should be mailed to the wordpress admin. I got to know how to Send automatic mail to Admin when user/member changes/adds profile but i don't have anything to do with the profiles right now. I want to send a mail to wp admin simply on button-click. Any help will be appreciated.
I could not really work out with the ajax with plugins things. Not so good with it still. :( So i simply used the function `get_bloginfo('admin_email')` to obtain the admin's email address. Using `mail()` function, the mails are sent to the obtained email address on click of the button.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "email" }
Post interior margin in twenty eleven theme I'm trying to customize the aspect of a single format post, in my case is "Link". I've added a different color background so they look different, editing the CSS as this: .format-link .entry-content { padding: 0; font-style: italic; background: #d7b5b5; //sfondo rosa } So they look like this: < I'm trying to add a margin between the color and the text in the way there's some free space (but with color background) on left and right side before the text. I've tried adding Margin and Padding values in the CSS but nothing happens, I think because the padding and the margin space take the white color instead of the pink... Can someone explain me? thanks a lot
Well, first, it's a pure CSS question. Second, `padding` is what you want to use. Just change `padding: 0;` to whatever you like. I just used FireBug to hack a padding of 1em into your code, and it worked like a charm. **// Edit** However, it is not just `.entry-content` but also **`.entry-summary`** that you want to affect. .format-link .entry-content, .format-link .entry-summary { padding: 1em; // for example font-style: italic; background: #d7b5b5; //sfondo rosa } **// Edit** \- again It seems, you have to work on your `style.css`. For singular posts, you already defined a different padding: .singular .format-link .entry-content { padding: 1.625em 0 0; } You either have to adapt that as well, or just delete it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, css, theme twenty eleven, custom background" }
Link to subpages on the same page I'm using a dropdown menu on my Wordpress page which shows all the pages. If you hover over it, the subpages of that particular page are shown. Say I have five pages that each have a couple of subpages. Is it possible to show the subpages on the same page as the page itself and have the dropdown menu link to the section of the page where the subpage is listed? Hope this is clear. thanks.
`get_children` is the most straightforward way to get "attachments, revisions, or sub-Pages". So... $children = get_children(array('post_parent'=>$post->ID)); if (!empty($children)) { foreach ($children as $child) { echo '<div id="child-'.$child->ID.'" >'; // content formatted however you want echo '</div>'; } See the Codex page for further parameters that you might need. I don't know how you've constructed your drop-down menu but you can link to any element on the page using its `id` attribute so your `href` for the links should be `#child-<ID>`, preferably constructed as an absolute URL.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "dropdown, sub menu" }
Extending arrays in parent theme without completely overriding the files I am new to all child-theming things and trying to override an array value which is declared in one of the php files. I also don't want to override the whole php file, because it has many other functions in that file that I don't want to duplicate. How can I do this? The `maintemplate-somefile.php` : ... $Icons = array( .... ); ...
I don't know exactly how your themes-- parent and child-- are constructed but the child theme's `functions.php` loads before the parent's. So, if this template is included via `functions.php` changes you attempt to make in the child `functions.php` to that `$Icons` array will be overwritten as soon as the parent `function.php` loads. Since you say this has "many other functions", it seems likely that this file is somehow included from `functions.php`. In fact, if `maintemplate-somefile.php` is included by any file that `$Icons` array will be overwritten, as per the code you posted there is no attempt to merge that array with pre-existing values. If this is a page template, and you provide a replace template, the parent template will not load at all. Your parent theme might have provided a hook that you could use, or there may be some other way to achieve the end you want, but given that you posted effectively no code it is hard to say much more.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, child theme" }
Getting all the users who have author privilege Can anyone tell me how to get all the users who have author privileges by querying the DB in WordPress and order them by number of posts written by them. I use the following query to get all the users from DB: $authors = $wpdb->get_results( "SELECT ID, user_nicename from $wpdb->users ORDER BY display_name" );
Unless you want to retrieve custom data from the database, you will hardly ever need to make use of the `WPDB` class (or its global object, respectively). Though it is obviously possible to do things that way as well. Just for the sake of completeness, _if_ you had a reason to not use a more abstract function, you'd have to employ `JOIN` in the select syntax as user roles live in the _usermeta_ table. But it'd be much simpler to make use of the `get_users` function: $args = array( 'role' => 'author', 'orderby' => 'display_name' ); $authors = get_users( $args ); **[EDIT]** As for the question in the comments (ordering by the number of posts): Use `'post_count'` as an argument for the `'orderby'` parameter (and read the linked codex page, which gives you all the possible arguments).
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "database, wpdb, users" }
How to load a different theme for categories? I need to load a completely different theme for my categories. My search came up with `switch_theme` function but it changes the theme permanently while I only need the theme change only occur on my category pages. Then I found this. add_filter( 'template', 'my_change_theme' ); add_filter( 'option_template', 'my_change_theme' ); add_filter( 'option_stylesheet', 'my_change_theme' ); function my_change_theme($theme) { if ( is_category() ) $theme = 'theme_for_cats'; return $theme; } The problem with this one is, it only loads the correct stylesheet. The markup stays the same as my default theme. Any help is appreciated.
Ok, after some consideration and tinkering I could get it to work. The reason it wasn't working was because the needed procedures for loading a template kick in long before the the parser gets to `functions.php` of the theme. So to overcome this I had to bring the code into the plugins' section. By creating a plugin the needed filters are called in time therefore the theme gets changed correctly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "themes, switch theme" }
Comments not displaying after changing theme The 'Leave a Reply' section at the end of my posts are not displaying after changing to the 'The Morning After' theme. Comments and reply sections are displaying when I revert to the Twenty Eleven theme. I have tried re-installing the theme but it is still not working. Example post at: <
After the kerfuffle of logging in and acquiring the theme, I got to the code: $comm = get_option( 'woo_comments' ); if ( 'open' == $post->comment_status && ($comm == 'post' || $comm == 'both' ) ) { comments_template( '', true ); } Your comments are not showing because in the woothemes settings, they have not been set to show for posts. In future I recommend you look through all options and configuration panels, a quick skim read should resolve these issues
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, comments" }
Action hook 'save_post' triggered when deleting posts I developed a custom plugin which rewrite some content of my posts, but when i move a post to trash, the action hook 'save_post' is triggered and the post is not deleted. A simplified version of my code : add_action('save_post', 'rewrite_post', 10, 2); function rewrite_post($post_id) { remove_action('save_post', 'rewrite_post'); $title = preg_replace('/\_/', ' ', get_the_title($post_id)); $my_post = array(); $my_post['ID'] = $post_id; $my_post['post_title'] = $title; $my_post['post_status'] = 'publish'; wp_update_post($my_post); add_action('save_post', 'rewrite_post'); } How can i prevent this hook getting triggered when i delete posts ?
It's probably easiest to just check the post status within your function. Untested: add_action( 'save_post', 'rewrite_post', 10, 2 ); function rewrite_post( $post_id ) { if ( 'trash' != get_post_status( $post_id ) ) { remove_action( 'save_post', 'rewrite_post' ); $title = preg_replace( '/\_/', ' ', get_the_title( $post_id ) ); $my_post = array( ); $my_post['ID'] = $post_id; $my_post['post_title'] = $title; $my_post['post_status'] = 'publish'; wp_update_post( $my_post ); add_action( 'save_post', 'rewrite_post' ); } }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "save post" }
Adding post thumbnail in programatically inserted post I want to insert post programatically so here is the code to add one: global $user_ID; $new_post = array( 'post_title' => 'My New Post', 'post_content' => 'Lorem ipsum dolor sit amet...', 'post_status' => 'publish', 'post_date' => date('Y-m-d H:i:s'), 'post_author' => $user_ID, 'post_type' => 'post', 'post_category' => array(0) ); $post_id = wp_insert_post($new_post); How to add a featured image to post and trigger it for testing ?
The post thumbnail is just saved as post meta with the key: `_thumbnail_id`. So after you insert the post and get the post id, you can set the post meta for that post. The `$thumbnail_id` is just the ID of the image you'd like to set as the thumbnail, up to you since I can't tell from your question what this should be. global $user_ID; $new_post = array( 'post_title' => 'My New Post', 'post_content' => 'Lorem ipsum dolor sit amet...', 'post_status' => 'publish', 'post_date' => date('Y-m-d H:i:s'), 'post_author' => $user_ID, 'post_type' => 'post', 'post_category' => array(0) ); $post_id = wp_insert_post($new_post); if( ! is_wp_error( $post_id ) ) update_post_meta( $post_id, '_thumbnail_id', $thumbnail_id );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "wp insert post" }
Converting timestamps to local time with date_l18n() I've got a WordPress cron job that sends an email periodically and saves the timestamp when it was sent as an option, and I'd like to display a date on a settings page. Something like, "The last email was sent on 'x'". I'm on the west coast of the US, so our time is currently seven hours off of UTC. My expected output from date_i18n(), passing it the timestamp, would be a locally formatted date with a seven hour adjustment from UTC. However, it returns the time in UTC. Even trying to get the current time doesn't return what I would think would be the expected output. For example: `echo date_i18n('F d, Y H:i');` outputs April 05, 2013 11:36 as expected, but `echo date_i18n('F d, Y H:i',time());` outputs April 05, 2013 18:36. Is this intentional? How can I return a locally formatted date from a preexisting time stamp? Thanks for any help.
I know I'm three months late, but the function you want here is WordPress' `get_date_from_gmt()`. The function accepts a GMT/UTC date in `Y-m-d H:i:s` format as the first parameter, and your desired date format as the second parameter. It'll convert your date to the local timezone as set on the Settings screen. Example usage: `echo get_date_from_gmt( date( 'Y-m-d H:i:s', $my_unix_timestamp ), 'F j, Y H:i:s' );`
stackexchange-wordpress
{ "answer_score": 34, "question_score": 18, "tags": "php, date time, wp cron" }
updating meta_key from the frontend I am wanting to update the meta_key in the database to reorder postmeta from the frontend. I'm using jQuery UI drag and drop to move items into an order, I can update the values but the meta_key is not so easy. My meta_key and values are like this: * add_task_0_assigned => value * add_task_0_complete => value * add_task_1_assigned => value * add_task_1_complete => value * add_task_2_assigned => value * add_task_2_complete => value * add_task_3_assigned => value * add_task_3_complete => value the values I can update from the frontend easily using super globals $_POST or $_GET but, is there a way to modify the meta_key to save and reorder in the database? Any help or guidance would be appreciated.
I don't have time for a detailed reply but some ideas: 1) Use arrays in the front end. Make your input ID's like `add_task_assigned[]` and `add_task_complete[]` \- these appear as arrays in the back end. It's not great practice, but it works. 2) Use an array in the backend. Store the meta as `array( [0] => array( 'assigned' => true, 'completed' => true ), [1] => array( 'assigned' => true, 'completed' => false ) )` 3) As we're not quite sure how you've structured the HTML, the serialize method of jQuery UI sortable may also be handy: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "front end, post meta" }
Structure for projects and clients I have a client who has requested a WP based portfolio where they will present their projects and clients, filtered by categories and tags. They also wish to filter all projects done for a particular client. I decided to use regular posts for the projects, but I'm unsure as to what would be a good setup for clients. My idea is to have a custom post type named clients, in which the user can create clients that are then made available in a custom field select list in each post. This would make for a robust structure but it seems a bit unnecessarily to have to use a custom post type simply to achieve this. Any ideas on a more effective approach?
It sounds like you need both clients and projects to have "post-like" capabilities, meaning that using a taxonomy for clients wouldn't make much sense. In this case, I would highly recommend the amazing "Posts 2 Posts" plugin by Scribu, found here: < The plugin allows you to create connections between posts, and makes it trivial to query posts based on these connections.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom post types, customization" }
Automatically Generated Menu pages I am a designer for a website, which I had a developer build in wordperss for me. Each time a new page is created, it is automatically added to my menu bar. Is this something the developer has built into the code, or is it something I can turn off?
There are two major things you need check for to resolve this. If your site is using the WordPress menus, then under Appearance | Menus is a checkbox that if ticked will automatically add all new top-level pages to the menu. Unticking that box will stop the behavior. If you check that area and no menus are defined, then the theme is using wp_list_pages() to generate a menu. If the menu bar appears at the top of the content, then check the theme's header.php file for the function. If your menu is on a sidebar, check for the function in sidebar.php. If neither of the above applies, you might check your Widgets to see if something there is doing it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Get page IDs from nav items I am trying to get all the IDs in my navigation and convert it to a string so that I can use it with `wp_query` to get the pages that are only listed in the nav. The code to get the IDs: $menu_name = 'primary'; if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] )) { $menu = wp_get_nav_menu_object( $locations[ $menu_name ] ); $menu_items = wp_get_nav_menu_items($menu->term_id); } foreach ( $menu_items as $menu_item ) { $numbers[] = $menu_item->ID; } $number = implode(',',$numbers); But it is returning the wrong numbers. When I go to the admin area and hover my mouse over the pages, the number that shows up in the address bar on the bottom of the screen doesn't match. What am I doing wrong?
Menu items are stored in the `posts` table with a `post_type` of `nav_menu_item`. So, what you are returning is the ID of the menu item itself, not what it points to. The page/post ID that the menu item refers to is stored in the `postmeta` table, with a `post_id` that matches the menu item `ID` and `meta_key` = `_menu_item_object_id`. The easiest way to get the `meta_value` (ie the page being pointed to by the menu item) is to use something like this: `$numbers[] = get_post_meta( $menu_item->ID, '_menu_item_object_id', true );`
stackexchange-wordpress
{ "answer_score": 15, "question_score": 13, "tags": "menus, id" }
Ordering stylesheet above <style> using functions.php I'm loading a stylesheet and a `style` into the header using functions.php. This works but the stylesheet is being presented below the `<style>`. I need to order the stylesheet **above** the `style` block. /*-----------------------------------------------------------------------------------*/ /* Load CSS into header /*-----------------------------------------------------------------------------------*/ function folio_dynamic_css() { wp_enqueue_style( 'theme', get_template_directory_uri() . '/assets/css/style.css', false, '1.0', 'all' ); ob_start(); echo '<style type="text/css">'; # css styles here echo '</style>'; # compress CSS $output = ob_get_clean(); echo preg_replace('/^\s+|\n|\r|\s+$/m', '', $output) ."\n"; } add_action('wp_enqueue_scripts', 'folio_dynamic_css', 1 );
You should not be outputting anything on the `wp_enqueue_scripts` hook, just enqueueing. Move your css output to a function hooked to `wp_head` with a lower priority than 8, which is when the enqueued styles are printed in `wp_head`: function folio_enqueue_css() { wp_enqueue_style( 'theme', get_template_directory_uri() . '/assets/css/style.css', false, '1.0', 'all' ); } add_action( 'wp_enqueue_scripts', 'folio_enqueue_css', 1 ); function folio_dynamic_css() { ob_start(); echo '<style type="text/css">'; # css styles here echo '</style>'; # compress CSS $output = ob_get_clean(); echo preg_replace('/^\s+|\n|\r|\s+$/m', '', $output) ."\n"; } add_action( 'wp_head', 'folio_dynamic_css', 20 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, wp enqueue script" }
Have a Custom Post Type index page display taxonomy items instead of posts I have a CPT registered that is called `lessons` with a custom taxonomy (category) that is called `courses`. I want the `/courses` page (archive-courses.php?) to display the individual courses (i.e. "online marketing", "paid advertising") and not the individual posts (lessons). Would this mean I'd just customize the loop, or a complete custom WP_Query?
If you'd like to list the individual courses, i.e. the taxonomy terms, you'd use neither `WP_Query` nor the WP standard Loop. Instead, make use of the `get_terms` function to retrieve the courses. It returns an array of term objects (if the taxonomy does exist and has terms matching the function arguments). Iterate over that and do something with it, such as displaying a list of links to the lessons: $courses = get_terms( 'courses' ); if ( $courses ) { echo '<ul class="course-list">'; foreach ( $courses as $course ) { echo '<li>' . '<a href="/courses/' . $course->slug . '" ' . 'title="' . sprintf( 'View lessons of %s', $course->name ) . '">' . $course->name . '</a>' . '</li>'; } echo '</ul>'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, taxonomy, custom post type archives, terms" }
Link or button to open the media manager from frontend I am trying to figure out if there is a way to add a link or button that will open the media manager/library on the front end of the site? I don't need to select images for insert or to select images as featured, I simply want to allow my users to upload and edit their media within the library without having to go the backend to do so. Is this possible? I've Googled quite a bit and can't seem to find anyone else who's trying to do this so I turned here.
Virtually all the core files and scripts that WordPress uses for displaying the media library are within the `wp-admin` folder, plus it uses various admin-only hooks, so using this on the front-end is pretty much out of the question. It's not difficult to allow users to upload to the media library from the front end (either writing your own system or using a plugin like Gravity Forms which has this functionality built-in), but providing all the media management functionality is going to be a very big task indeed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media library, front end" }
How can i remove all html tags from get_the_content()? i want to remove all html tags from content like `<p>, <br>, <img>, <a>` i `tried strip_tags()` also tried $content = get_the_content(); $content = apply_filters('the_content', $content); but not working for me. any reliable solution ??
The WordPress function, at least the one I tend to use, would be `wp_filter_nohtml_kses`. That should remove all of the HTML, but you need to be careful not to put some HTML back by running `the_content` filters on your HTML-less string. I am not sure why `strip_tags` didn't work, but I suspect that you doing something else in other code posted or not posted and that that something else is undoing your tag stripping, or putting some tags back. Mainly I think that because you tried ... $content = get_the_content(); $content = apply_filters('the_content', $content); ... and apparently expected tags to be stripped?
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "php, the content" }
the_time() returning wrong date/time (way in the future) Within a loop, that otherwise works fine, `the_time()` is giving me a date and time about 25 days and a few hours ahead of the actual date. For instance, if I post today, it lists it as "April 30th, 2013" (today is April 6th, 2013). I can't for the life of me figure out why it's doing this. A couple things: This is on the front-end of my site and I am looping through a users posted attachments (sort of like a front-end media manager). The loop is working fine to grab the thumbnail, the attached post (and it's date), etc but the time of the actual upload of the file is just not right. That being said, the date/time that lists in the wp-admin section is correct, which is even more confusing... Pastebin of the entire page
> if I post today, it lists it as April 30th, 2013 (today is April 6th, 2013). # Your using a lowercase t in your date format string. t Number of days in the given month 28 through 31 On Line 92: `echo get_the_time('M-t-y \a\t g:ha' , $id);` I think you meant to use d or j instead.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "attachments, media, front end" }
Search WooCommerce Products in WordPress I've noticed that my WooCommerce products are not searched by the default WordPress search function. Any idea how to modify the function to ensure that products and product tabs are searched?
Just extend your search form with a hidden input: (notice the last input field) <form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>"> <label> <span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ) ?></span> <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" /> </label> <input type="submit" class="search-submit" value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>" /> <input type="hidden" value="product" name="post_type" id="post_type" /> </form>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "search, plugins" }
Javascript 2 elements dependent onclick .toggle Hi I have two JavaScript elements for logging into and create an account. They both overlap each-other when the div id is clicked and I need them to hide when the other id is clicked and vice versa. <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#sign-in').live('click', function(event) { jQuery('#login-content').toggle(); }); }); jQuery(document).ready(function(){ jQuery('#create-account').live('click', function(event) { jQuery('#create-content').toggle(); }); }); </script>
Since you want them to alternate the easiest would be to use `show()` and `hide()` rather than `toggle()`, since you don't actually want to toggle the visibility if the login is clicked more than once, you want it to always show the #login and hide the #create. Also note that the `live()` function has been deprecated in favor of `on()`. See this example: jQuery(document).ready(function(){ jQuery('#sign-in').on('click', function(event) { jQuery('#login-content').show(); jQuery('#create-content').hide(); }); jQuery('#create-account').on('click', function(event) { jQuery('#create-content').show(); jQuery('#login-content').hide(); }); });
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "javascript, troubleshooting" }
Get author ID with attachment ID I have a page, outside the loop, that display a media attachment with some basic info about it (title, uploaded date, etc). I have the attachment ID available to me via a form submitted before the page loads. What I need to do is secure the page by making sure that only users who have uploaded that file have access to the page with that file one it. In order to do that, I assumed the easiest way would be to compare the ID of the current, logged-in user with the ID of the user who created the attachment. But there doesn't seems to be a way that I can find to get the ID of the author of a post outside of the loop using only the attachment ID. I'm stumped, how should I do this?
Back in the day I wrote a function to check for that (you can put it in **functions.php** and call it from your page): public function check_if_user_is_author($user_id, $post_id) { global $wpdb; $res = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->posts ." WHERE ID = %d AND post_author = %d LIMIT 1", $post_id, $user_id)); if(isset($res) && count($res) > 0) { return $res[0]; } else { return false; } } Also, theoretically you could just get the post object and compare the author's ID with the current logged in user's ID. Disclaimer: code below is untested. $current_user_id = get_current_user_id(); $post_data = get_post($your_att_id, ARRAY_A); $author_id = $post_data['post_author']; if( $current_user_id == $author_id ) { // good, current logged-in user is author of attachment }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "images, author, id" }
Header links also appearing in the footer In my menu area of the word press admin I have access to place links in both the h "main menu" and the "footer links" register_nav_menus(array( 'main_nav' => 'The Main Nav', 'footer_links' => 'The Footer Links' )); In the Header: wp_nav_menu(array('menu' => 'The Main Nav')); In the Footer: wp_nav_menu(array('menu' => 'The Footer Links')); In the header Nav, I have a link to the default sample page, in the footer I have a link to google. I save the menus and look at the front end, I get the sample page link in both the header and the footer. for further proof that I have two menus: ![enter image description here]( What's going on?
The correct way to get a specific menu is the `'theme_location'` parameter: wp_nav_menu(array('theme_location' => 'main_nav')); wp_nav_menu(array('theme_location' => 'footer_links'));
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, menus" }
Custom Post Type Meta Boxes How would you make a meta box sit above all other meta boxes at all times in a custom post type? For example: add_meta_box ( 'aisis-meta-id', 'Mini Feeds Information', array(&$this, 'aisis_mini_feeds_info'), 'mini-feed', 'advanced', 'high' ); Create a meta box, how ever it only appears after ALL other meta boxes, be they plugin or system wide. I need my meta box to sit directly under the editor at all times.
Change `advanced` to `normal`, this will at least move it up above some others. However, there's no guarantee you get the top spot, because a user can still drag and drop metaboxes around, or a core metabox or one added by another plugin might believe it is more important than yours. There's no way for WordPress could offer the top spot as an option, as what would happen when two plugins decided they both wanted it? p.s. here's how to move Yoast's SEO plugin metabox down: add_filter( 'wpseo_metabox_prio', 'move_yoast_metabox_down' ); function move_yoast_metabox_down( $priority ) { return 'low'; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "custom post types, metabox" }
How to check if a theme is active? I'd like to be able to check if the twentytwelve theme is active. I know if I was checking for an active plugin I'd do something like: $active_plugins = apply_filters( 'active_plugins', get_option( 'active_plugins' ) ); if ( in_array( 'plugin-folder/plugin-folder.php', $active_plugins ) ) { //do stuff } else { add_action( 'admin_notices', 'create-a-notice' ); } What's the proper way to check if a theme is active so I can run a function for that theme?
You can use `wp_get_theme`: <?php $theme = wp_get_theme(); // gets the current theme if ( 'Twenty Twelve' == $theme->name || 'Twenty Twelve' == $theme->parent_theme ) { // if you're here Twenty Twelve is the active theme or is // the current theme's parent theme } Or, you can simply check if a function in twentytwelve exists -- which is likely less reliable; a plugin, or even another theme, could declare `twentytwelve_setup`, for instance. <?php if ( function_exists( 'twentytwelve_setup' ) ) { // Twenty Twelve is the current theme or the active theme's parent. }
stackexchange-wordpress
{ "answer_score": 27, "question_score": 16, "tags": "plugins, themes, activation" }
How to use get_template part in the plugin? I was using the entire template in the plugin, but I would like to use get template part, so that I can reuse the header and footer in the original template. The code is like this: add_filter( 'page_template', 'template_reg' ); function template_reg() { if ( is_page( ourdoctors_single_pg() ) ) { $page_template = dirname( __FILE__ ).'/templates/OurDoctors.php'; return $page_template; } Is there any way that I can use partial template instead of entire template? I tried to use `get_template_part`, but it seems like I have to put template in the theme. But how to put the template in the plugin?
Yes, `get_template_part` will always look in the theme. It uses `locate_template` which is hard-coded to use `STYLESHEETPATH` and `TEMPLATETPATH` I don't know exactly what you mean about using a "partial template", but if you mean "can I include part of a PHP file?" then no. It is all or nothing. You need to break your file into multiple files or break the file's contents into granular functions that you can call as needed.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "plugins, theme development, themes, templates, page template" }
Is it possible to block subscriber users to changing its password? I want to disable changing password option for all my subscriber users. Is it possible by doing any code tweak or something using any plugin? !Disable password changing option for subscriber users If someone has any idea or plugin knowledge to do this then appreciated.
You can try if( current_user_can( 'subscriber' ) ) { add_filter( 'show_password_fields', '__return_false' ); } see also < <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, users, permissions, password" }
Access for adding subpages but not for pages For every website project, i make the wordpress admin custom for the client. Right now, i want that the client only has access to add subpages. I have a main navigation on the website. I want that the main navigation is fixed, so the client can not add pages to the navigation. But the client can add subpages to the current pages in the fixed main navigation. I googled it, but i can't find a solution. I know i can show menu items on a specific id. So i can make the main navigation fixed. Example: <?php wp_list_pages('include=7,13,26,35&title_li=<h2>' . __('Pages') . '</h2>' ); ?> But, does it show the subpages id's thats below the page id? And is there not a cleaner way? Because with this solutation the client has still access to create pages. I only hide the created pages on the front website. Hope someone can help me. Many thanks,
`wp_list_pages` simply lists pages. It isn't a menu and doesn't use the navigation menu APIs. For what you want you'd need to do several queries to find the subpages of those page IDs, so in your case 4 queries, and you'd need to do 4 wp_list_pages calls, and a manual query to get the top level pages. This will not be fast, and is wasteful, kludgey, and a bad idea. So instead you should be using `wp_nav_menu`. Use a standard nav menu, if your client modifies this then charge them to put it back ( serves them right, they were warned, but it is their site, and they paid for it, so why shouldn't they be able to? ). With a standard nav menu you can add non-page items, rearrange items, and submenu items don't have to follow the page structure.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "admin, sub menu, user access" }
Show the title of the latest post by author I have the following function which I use to show the author name,author avatar and the author biography in a div. I need to show the title of the latest post by the author along with this. Can anyone help? function ajaxified_function() { $response = new WP_Ajax_Response(); $id = $_POST['author_id']; $auth_name = get_the_author_meta('display_name', $id); $avatar = get_avatar($id); $desc = get_the_author_meta('description',$id); $auth_desig = get_the_author_meta('designation', $id); $output = "<div id='bloggers_title'>$auth_name</div>\n <div id='bloggers_desig'>$auth_desig</div>\n <div id='bloggers_avatar'>$avatar</div>\n <div id='bloggers_desc'>$desc</div>\n"; $response->add(array( 'what' => 'has', 'data' => $output )); $response->send(); }
You can get the latest post of an author adding the following code to your function: $latest_post = get_posts( array( 'author' => $id, 'orderby' => 'date', 'numberposts' => 1 )); // Since get_posts() returns an array, but we know we only // need one element, let's just get the element we need. $latest_post = $latest_post[0]; Then modify your `$output`, adding the data you need (specifically `guid` for the permalink, and `post_title` for the title), for example: $output .= "<div id='bloggers_latest_post'> <a href='$latest_post->guid'>$latest_post->post_title</a> </div>"
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "posts, author, get posts" }
Rename "Add Media" Button To "Add Images" I would like to rename the "Add Media" button (just above the post editor interface) to be "Add Images". I can't seem to find the appropriate filter for this. There seems to be a filter that has now been deprecated but I can't figure out what the new method is. The legacy filter was `media_buttons_context`.
The button text being a translatable string, you can make use of the gettext filter: function wpse95025_rename_media_button( $translation, $text ) { if( is_admin() && 'Add Media' === $text ) { return 'Add Images'; } return $translation; } add_filter( 'gettext', wpse95025_rename_media_button, 10, 2 ); For the sake of completeness: Of course, you can also keep the new string translatable. function wpse95025_rename_media_button( $translation, $text ) { if( is_admin() && 'Add Media' === $text ) { return __( 'Add Images', 'your-text-domain' ); } return $translation; } add_filter( 'gettext', wpse95025_rename_media_button, 10, 2 );
stackexchange-wordpress
{ "answer_score": 10, "question_score": 3, "tags": "media" }
Why is this page using the homepage template and not the one it should? * * * One of my clients has installed a theme where when a visitor enters their username and email to register as a new user they get shown a link to download a custom report file. This was working fine on my clients test installation, but now they've converted the site to a live site the download link doesn't show and instead the page uses the homepage template... I'm stumped as to why it's happening so any advice would be great. Here's the test page Here's the live page Here's a jsFiddle of the PHP code
The difference between the two is that the test site has pretty permalinks enabled and the live site doesn't. If you look at the URL, the issue becomes apparent, this is not a valid URL/query string: If you change the second `?` to an ampersand, the page renders correctly. Either enable pretty permalinks on the live site, or modify your code with `add_query_arg` to correctly append the additional query argument: <input type="hidden" name="redirect_to" value="<?php echo add_query_arg( 'register', 'true' ); ?>" />
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates, redirect" }
IF Custom field value equals ZERO I am trying to use the following code to check for my custom field for a value of ZERO to then display my div <?php $mp_price_sort = get_post_meta('mp_product_price'); if ($mp_price_sort == '0') { ?> <div><?php echo do_shortcode('[shortcodes]'.$mp_buy_button.'[/shortcodes]'); ?></div> <?php } ?> However it is interperting as a value of anything, thus displaying the div, but I need it to check for the number 0. How can I fix this?
You are using get_post_meta incorrectly, so it is returning FALSE every time. As PHP equates '0' and FALSE, your div will always be displayed. The correct syntax for get_post_meta is: <?php $meta_values = get_post_meta($post_id, $key, $single); ?> where $post_id is the only required argument.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, shortcode, post meta, variables, meta value" }
displaying an error before update_post_meta I'm trying to restrict how many items you can associate with a post so in my save function I have: add_action( 'save_post', array( $this, 'save_custom_items_data' ), 10, 2 ); public function save_custom_items_data( $post_id, $post ) { if(count($related_items) > 5) { // display error message here but the page redirects anyway... } else { update_post_meta( $post_id, '_custom-meta-items', $related_items ); } } how do I display an error here instead of saving the custom post meta?
Short of doing some jQuery validation, I think the only option is `wp_die()`. add_action( 'save_post', array( $this, 'save_custom_items_data' ), 10, 2 ); public function save_custom_items_data( $post_id, $post ) { if( count( $related_items ) > 5 ) { wp_die( 'Error, 5 items max.', 'Error', array( 'response' => 500, 'back_link' => true ) ); } else update_post_meta( $post_id, '_custom-meta-items', $related_items ); } Related Q&A's: * Incorrect data after modifying post using backlink from wp_die * Require tags for bbPress topics
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin, post meta, save post" }
How to use shortcode inside of shortcode in theme I am trying to place a shortcode inside another shortcode within a page template, however the various attempts I've made seem to not do anything. Here's how my code looks now - <?php echo do_shortcode('[shortcode]' .$shortcode2. '[/shortcode]');?> I've also tried these - <?php echo do_shortcode('[shortcode]$shortcode2[/shortcode]');?> <?php echo do_shortcode('[shortcode]{$shortcode2}[/shortcode]');?> What am I doing wrong?
Have you tried setting the output of the first do_shortcode inside the second call? $output = do_shortcode('[first_shortcode]Some content[/first_shortcode]'); echo do_shortcode('[second_shortcode]'.$output.'[/second_shortcode]');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, custom field, shortcode, page template, variables" }
Query for first 3 posts to change the look and feel Is there a way to query for the first three recent posts and then change how they display on the front page? I want the first three posts of my blog to show differently than the rest of them i.e. they will have full images, and my other posts will just have thumbnail previews. Thanks for any help in the matter.
You can style the first 3 posts differently without querying them separately, you just need to check where you are within the loop while outputting each post via the built in `current_post` var. while( have_posts() ): the_post(); // are we on the first page and outputting one of the first 3 posts? if( !is_paged() && $wp_query->current_post < 3 ): // output full image, etc.. else: // not first page and not first 3 posts // output just thumb, etc.. endif; endwhile;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, wp query, query posts, query" }
Error: Declaration of MyClass::start_lvl() should be compatible with that of Walker_Nav_Menu::start_lvl() I'm currently working on a WordPress site and whenever in the admin I go the Appearance > Menus page I get the following error: > ErrorException: Runtime Notice: Declaration of Walker_Nav_Menu_Edit::start_lvl() should be compatible with that of Walker_Nav_Menu::start_lvl() in wp-admin/includes/nav-menu.php line 203 It seems like some sort of PHP compatibility issue. I'm running PHP 5.3.10 on my local dev machine. What would be the best way to remedy this problem?
From `class Walker_Nav_Menu`: function start_lvl( &$output, $depth = 0, $args = array() ) Your child class _must_ use the same signature: three arguments, the first one passed by reference. Every difference will raise the error you got. Note that `$args` defaults to an empty array, but you get an instance of `stdClass`, not an array. This is WordPress.
stackexchange-wordpress
{ "answer_score": 30, "question_score": 17, "tags": "menus, errors, compatibility" }
Customized landingpages for categories When I click on a category now, it looks like.. > Category Archives: MyCategory > > first post > > second post > > third post.. I want to customize these landing pages for special categories, add text, pictures, html. How do I do that, easiest way, w/o plugins. There might be a file to be cloned, like content-category-mycategory.php?
Here is the Template Hierarchy, which gives you an overview of the different approaches. You could create for each category an individual PHP file: * either `category-{CATEGORY ID}.php` * or `category-{CATEGORY SLUG}.php`. Or you could use a single file `category.php` in which you define the output (as well as its layout, style etc.) according to the current category - again, either depending on its ID or its slug. Here's a short example using the ID: $category = get_the_category(); $cat_ID = $category[0]->cat_ID; switch ($cat_ID) { case 'A': ... break; case 'B': ... break; default: ... }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories" }
How can i retrive a text from a custom field I retrieve the date of an actor by selecting the date. `'data_nasterii'` is the name of the custom field. <?php $data = get_field('data_nasterii'); echo date("d/m/Y", strtotime($data)); ?> If i do not select anyting, I'd like to return: `N/A` for the actor birthday. How can I integrate in this code? If there's a value: Ex: Birthday :22/11/1978 If I don't select anything I want: Birthday: N/A
I'm not certain what an empty `get_field` returns, as it's from a plugin. However, assuming it provides `FALSE` or an empty string: <?php $data = get_field( 'data_nasterii' ); echo ( $data ? date( "d/m/Y", strtotime( $data ) ) : 'N/A' ); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field" }
Output custom field as ul list I have a custom field who's content I would like to output as a ul list. The custom field contains words that are separated with a spaces between. I'm trying to use this code here but it's not working. <?php $list_items = get_post_meta($post->ID, 'idid'); if($list_items){ $list_items = explode(" ", $list_items) { echo '<ul>'; foreach($list_items as $list_item) echo '<li>' . $list_item . '</li>'; echo '</ul>'; } } ?>
You are using `get_post_meta` incorrectly. As you use it, it will return an array - you cannot explode an array. See the codex on get_post_meta(); If you pass `true` as the third parameter, this tells the function to return a string. So, $list_items = get_post_meta($post->ID, 'idid', true); should work.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field" }
Issue with WordPress native theme customizer function and jquery ui tabs So I am using the customizer in my theme which have tabs in the page utilizing jQuery UI Tabs. When I load up the customizer, it would the sidebar accordion would be sluggish and the preview page would duplicate the content and the tabs would not render correctly. This is very strange and it does not produce this issue when you just go to the page on its own ( not in the customizer preview ). I am also not seeing any errors from my browser console in terms of JS script. So to test, I disabled the jQuery tabs and everything works in preview customizer again...So it is somehow related to that but I just don't know what. Has anyone encountered this?
It turns out this is indeed a bug. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization" }
Child theme only loads on home page I was having the following problem: I created a child theme, it was 'correct', technically. It even worked and displayed the proper changes, and when I navigated to sub-pages (ie not the home page), the child theme's effects seemed to vanish.
I scoured the code in the parent theme for any clues, I found none. The one clue I found was that the 404 page worked as expected, which tipped me off that something was up with the page-templates. To resolve the issue, I opened a post, changed the page template to another one (for example "contact form"), updated, then changed it back. I have no idea why that worked, it appears to be a wordpress bug.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child theme" }
Multi Site Setup, Child Themes, Getting Style Sheet Directory As the title says, I have a multi-site setup and the apperance is customized with child themes. > The main site: **themainsite.com** > > Secondary site **foo.com** When you look into the source code of foo.com, you see some URLs referencing to the mainsite. Such as: <link rel="stylesheet" href=" type="text/css" media="screen" /> I checked wordpress documentation for get_stylesheet_directory_uri, but could not find an answer. Is it possible to remove these kind of references to the main site? **UPDATE:** All the CSS/JS references are handled in the **header.php** of the parent template like below. I already have a header.php oin my child theme which overrides the parent theme's header.php. <link rel="stylesheet" href="<?php echo get_template_directory_uri() ?>/css/some.css" type="text/css" media="screen" />
I fixed it with changing the multi-site setup from sub-folders to sub-domains.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, multisite" }
Plugins try to install in old location I just moved my WordPress website to a new domain & server. Everything seems to work fine except for installing new plugins. When I'm trying to install a new plugin, it's still trying to access the upload directory of the old server. The error I get is: Warning: touch() [function.touch]: Unable to create file /home/oldserver/domains/olddomain.com/public_html/website/wp-content/uploads/search-and-replace.tmp because Permission denied in /home/newserver/domains/newdomain.com/public_html/wp-admin/includes/file.php on line 179 Warning: unlink(/home/oldserver/domains/olddomain.com/public_html/website/wp-content/uploads/search-and-replace.tmp) [function.unlink]: Permission denied in /home/newserver/domains/newdomain.com/public_html/wp-admin/includes/file.php on line 493 I already changed the `WordPress URL`, `Site URL` and `Upload Directory` in the database `wp_options` table. What did I miss?
In `wp-config.php` under the different salts there was a line, which I missed because it was directly under the different salts. define('WP_TEMP_DIR', '/home/oldserver/domains/olddomain.be/public_html/website/wp-content/uploads'); Obviously that needed to be changed to the new server path as well.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "installation" }
How do I create a post_id column, for admin posts list? I'm trying to add a column to display the post_id from the wp_postmeta table. I would like to display it in the admin posts list. Here is my code: add_filter( 'manage_edit-movie_reviews_columns', 'my_columns' ); function my_columns ( $columns ) { global $post; $columns['id'] = 'ID'; return $columns; } add_action( 'manage_posts_custom_column', 'populate_columns' ); function populate_columns( $column ) { if ($column == 'id'){ echo $post_id; } } The ID column is visible, but no post_id are in that column- it is just blank. Please can you suggest changes. I'm new to wordpress development so please be gentle.
You haven't set `$post_id` so there is no reason is should display. If you have debugging enabled as you should when you are working, you would have spotted the error immediately. What you need to do is: add_action( 'manage_posts_custom_column', 'populate_columns' ); function populate_columns( $column ) { global $post; if ($column == 'id'){ echo $post->ID; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin" }
comments_number display outside specified span I want to display the number of comments a particular post has, so i thought i'd use comments_number, however when i use this the comment number gets printed outside of the span it's supposed to be contained within. I tried using get_comments_number too, but that instead displays nothing at all. The code below has been added to my functions.php amongst other code, but i just cannot get the comment number to display inside the span - it just prints at the top of the page. $content .= '<p class="meta"><span class="date">'.$date.'</span><span class="comments">'. comments_number() .'</span></p>';
`comments_number` doesn't return the number of comments, it echos it out. As the codex clearly states: > Use `get_comments_number()` to retrieve the value.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, functions, comments" }
Post's ID pattern? Each post has an ID and I would like to know how they were assigned. Is there a pattern? Why are the ID's not being incremented by 1 every posts? It would be easier..My ID's go from 9867, to 9869, to 9864, etc.. I can't seem to find a pattern. I could use "The Loop", but I'm doing that from another site. I want to include the last 30 posts of my wordpress site, so I need to find a pattern in the url to get the last 30 posts.
Each auto-draft gets its own ID, each revision, each nav item, page, custom post type … The actual ID of a post should be irrelevant, this is really just needed for the database and ugly permalinks. You cannot get the last 30 items by inspecting the post ID only. Install a REST API on the other site and a rule to get the last x items.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, urls, include" }
Where can I create a normal php file? I have a wordpress site and I want to create a normal php file. If I put it anywhere in my wp-content folder, I always get a page not found error when I try to access it. For example, I create a file: json.php, and I put it in the wp-content folder and try to acess it like that: www.example.com/json.php, but I get the error. If I put it outside my wp-content folder, it works, but then I can not use the Wordpress functions like The Loop. How can I create a php file in wordpress and acess it normally?
> For example, I create a file: json.php, and I put it in the wp-content folder and try to acess it like that: www.example.com/json.php, but I get the error. That is because the path is wrong. If you put the file in your theme the path to the file is ` not ` That path points to the server document root, not to a file in your theme directory. WordPress and the server conspire to lie about the location of files, at least when pretty permalinks are on. If they are off you will notice that most requests go through `index.php` and pages are loaded via various `$_GET` parameters but are not loaded directly. It is not clear what you are trying to do but you can 1. Use the correct path to the file 2. Put the file in the document root 3. Create a custom page template that will work with WordPress' rewriting mechanisms 4. Rewrite the path yourself using `.htaccess` rules. 5. Use the AJAX API if appropriate
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "php" }
Adding code to the function file I would like to move my large php functions out of the index or template files and into the function.php file. Would it be something like this? function grab_code(???) { ??? .= '<div>some HTML-PHP code I monkeyed together</div>'; return ????; } add_filter('???', 'grab_code'); Then in the template files i would add? echo grab_code(???); I found answers here that look close to what I am asking but the seem specific to a function. Thanks.
If you move the function and the add_filter function to the functions file, the you don't need to echo the function after. If the function doesn't involve using add_filter then you could echo out the function in your template file. Placing it in the functions.php file, will run on every page/post load unless specified otherwise.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, theme development, functions" }
Plugin or script to apply updated media settings to all featured images I need to know if there exists a script or plugin that will add a button the "Settings > Media Settings" that will rebuild all thumbnails to match the current media size settings. The problem this seeks to solve is when the site owner decides he/she would like different thumbnail and featured image sizes after having uploaded several at the wordpress default settings of 150px, 300px, 1200px This solution would allow users to auto resize the images in one click to match the current settings.
I install Regenerate Thumbnails on pretty much every single website I build. It does exactly what you need and I've never had a single problem with it. You can either resize them all at once in bulk through a tools submenu, or you can do individual ones in the media library.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, media settings" }
How to check if a custom user profile field is empty i have this code to limit the comments per user. <!-- #only one comment --> <?php global $current_user,$post; $usercomment = get_comments(array('author_email' => $current_user->user_email, 'post_id' => $post->ID)); if($usercomment) { echo "Thank you!"; } else { comment_form(); } ?> How can edit this code to also check if a custom user profile field [phone] is empty? If is empty display a message else display the comment form. Thank you.
You can check the user meta for the key you want: if ( get_user_meta('phone') !='' ) { echo "Your phone is not set"; } else { comment_form(); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization" }
What does this number represent in JetPack stats? !enter image description here When signed into my blog, this graphic is up on top. I know it shows visitor pattern over 48 hours, but does anyone know what the number represents? I searched on the WP site, and am not finding this. Note to the closer - Jetpack is not 3rd party, it's owned by the WP people and part of the normal installation. ![enter image description here](
When you sign in, You can see tiny site stats chart(displayed in above screenshot) in your toolbar called a Sparkline. The number in Sparkline represents the highest number of visitors visited in 48 hours of day. You can find more information in wordpress.com Stats Support. I have copy pasted the content below from this link so that it will not affect if that link ever changes its content in future. > You can also access your Site Stats page via the tiny stats chart in your toolbar called a Sparkline. The chart consists of 48 upright bars representing the last 48 hours of page views for the current blog, with darker lines indicating nighttime page views. Note that the toolbar will only appear when you’re logged in to WordPress.com.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugin jetpack, statistics" }
Woocommerce - Specific template for product category? I'd like to create a specific template for specific category (not for single product). Is it possible and how to do it? Thanks,
You can create specific template for specific category using taxonomy-product_cat.php template. For more information visit this page.
stackexchange-wordpress
{ "answer_score": 15, "question_score": 13, "tags": "plugins" }
How to debug | Some times the "Save Draft" button seems to spin but does not actually save I am using wordpress 3.5.1 and lately there seems to be a recurring problem with the save draft function where it seems like the draft was saved (i.e the wheel finishes spinning without an error message) but alas, all edits are lost. This happens both in the regular editor as well as in the distraction free wring space (where it is extremely frustrating, as all edits are lost when returning to the regular editing mode). I couldn't find a discussion about this problem in the other forums or any instructions on how to debug this or find the source of the problem. Any help will be much appreciated.
In wordpress root directory,open file wp-config.php,and find this code: define('WP_DEBUG', true); and just set the value to false somehow like this: define('WP_DEBUG', false); so that all errors will display,hope this can be helpful to u! and also the best way is to resintall wordpress if it's convient to u
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "save post, draft" }
Wp admin - Set default value to 999 in comments When you are at the comments menu in wp-admin you only see 20 comments at the time, so if you want to delete alla comments you can **ONLY** mark the 20 comments you see on current page. It dosent mark comments that are on the next page. Found a solution but dont know where to look for it In WP-admin -> Screen layout there you can see that its only set to 20 comments a page. I know that i could just access the screen layout and set it to maximum (999 comments a page). Now the question is can I set that value (999) to default for every user i create ? Or just basicly for the whole network? **Follow question:** : If its possible, then whats the best way to do it ? **NOTE** : Im using latest WordPress version with Multisite network.
You can use add_filter('edit_comments_per_page', 'return_999'); function return_999(){ return 999; } since the user options are filtered in the `WP_List_Table::get_items_per_page()` class method : /** * Get number of items to display on a single page * * @since 3.1.0 * @access protected * * @return int */ function get_items_per_page( $option, $default = 20 ) { $per_page = (int) get_user_option( $option ); if ( empty( $per_page ) || $per_page < 1 ) $per_page = $default; return (int) apply_filters( $option, $per_page ); } So you could do the same for `edit_post_per_page` and `edit_page_per_page`. Or if you have other custom post types: `edit_{CPT}_per_page`.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "functions, comments, wp admin, screen layout" }
Wrong date returned by get_the_time I have this line of code : $registration_date = get_the_time('F j, Y').' at '.get_the_time('g:i a'); I just ran this on my BlueHost hosted website and it returned : January 29, 2013 at 12:54 pm However, on the same site I can see in the dashboard that post publication dates are correct.
get_the_time() function returns the time of the current post within loop. If you want to display today's date then use date function of core php.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "date" }
Remove wrong dashes from get_the_title() I have a particular CPT post that has a dash (-) in its title. I copy this title in a variable `$var` using `get_the_title()` then I create a custom field somewhere else with a value equal to `$var` : `add_post_meta($my_post_id, 'some_name', $var);` Problem: in the custom field, the dash became a HTML entity with a "&", "#" and a 4-digit number number. Why, and how to fix the problem?
`get_the_title()` is treated with `wptexturize()` by default. That changes the dash. To fix it remove the filter and reapply it if it was really set: $wptexturize = remove_filter( 'the_title', 'wptexturize' ); $title = get_the_title(); if ( $wptexturize ) add_filter( 'the_title', 'wptexturize' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, custom field" }