INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Allowed memory size of 268435456 bytes exhausted (tried to allocate 64 bytes)? I am getting this error. I have increased the memory limit upto 512M. I have more than 4000 posts with so many data. Website is working fine. But when I am trying to access the custom post type page in admin section to see posts of that custom type this shows the error. I have read this blog also here. I think the problem is with the php script on edit page template. `select * from table where ....`. How can I edit this custom post type template page to limit the number of posts in admin section on custom post type. I think this is somewhere in wp-admin folder. Or there is something else I misunderstood about the infinite loop. Please suggest me . Increasing the memory limit in config.php is not working for me.
The problem was the max memory limit. I had defined in config.php define('WP_MEMORY_LIMIT', '512M'); But this was not working for me. But then I see , I need to define this define( 'WP_MAX_MEMORY_LIMIT' , '512M' ); also in config.php. Now custom property type is working for me. Now I can edit this post type.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php" }
Re-order posts in query after For a particular category I needed to merge in another custom post type. Now I would like to resort the query based on a custom field. Is this possible? Below is the way I've merged the queries. if (in_category( 'Events' ) && is_archive()) { global $wp_query; $args = array ( 'post_type' => 'custom_post_type' ); $second_query = new WP_Query( $args ); $wp_query->posts = array_merge( $wp_query->posts, $second_query->posts ); $wp_query->post_count = $wp_query->post_count + $second_query->post_count; } Thanks!
Given that meta is cached inside page load it should be reasonably performant to do it like this (not tested): usort( $wp_query->posts, function ( $post_a, $post_b ) { $a = get_post_meta( $post_a->id, 'key', true ); $b = get_post_meta( $post_b->id, 'key', true ); if ( $a == $b ) { return 0; } return ( $a < $b ) ? - 1 : 1; } ); It might be more reasonable to modify query inputs before it's run though, as per comment.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom post types, wp query, order" }
Search posts missing a particular custom field I am trying to search for posts that do not have yet set a particular custom field. The problem is that query down below returns an empty result. $args = array( 'post_type' => 'post', 'posts_per_page' => 5, 'meta_query' => array( array( 'key' => 'verified', 'value' => 'yes', 'compare' => 'NOT LIKE' ) ) ); $query = new WP_Query( $args );
Try using 'NOT EXISTS' instead of 'NOT LIKE' and remove the value ( it'll be removed by WP with NOT EXISTS ): $args = array( 'post_type' => 'post', 'posts_per_page' => 5, 'meta_query' => array( array( 'key' => 'verified', 'compare' => 'NOT EXISTS' ) ) ); $query = new WP_Query( $args ); <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp query, custom field, search" }
Looking to Customize YouTube Video Embeds I am looking to embed youtube videos into my posts and publish them as custom post types (videos). I would like to be able to append the options for getting rid of the information bar, starting the video at a certain spot, and autoplaying the video upon load. However, when I insert the link in the post currently, it spits out an ugly placement of the video. The video frame does not even fit within the post but stretches over the sidebar. Take a look here: < I have tried appending the customization to the end of the link with no success. Is the only way to customize YouTube embeds with a shortcode and if so how could I go about doing this?
This might help. On the YouTube video page, choose Share, then choose Embed, then choose Show More. Remove checks in boxes for "Show Player controls" and "Show Video Title and Player Actions." Choose largest given width size or custom size that is equal to or slightly greater than your div container width. Copy the code. Paste the code into your post, then change the width number to width="100%" and adjust the given height number until it works well on preview post. (You need an absolute height number. Setting height to "auto" or to a percentage won't work.) (No experience with autoplay.)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, shortcode, videos, youtube, oembed" }
Get images from the post Using `Add Media` I am inserting images in the Post.I want to reterive these only these images on the single post page.I am using `get_attached_media` function to reterive these images.But it returns an empty array. <?php $media_image = get_attached_media( 'image', $post->ID ); //print_r($media_image);?> <div class ="single-post-flex-slider"> <ul class="slides"> <?php foreach($attachments as $image){ $image_attr = wp_get_attachment_image_src( $image->ID,array(500,500) ); ?> <li> <img src="<?php echo $image_attr[0] ?>" width="<?php echo $image_attr[1] ?>" height="<?php echo $image_attr[2] ?>" /></li> <?php } ?> </ul> </div>
The Image added by `Add Media` is included in the Content.So I have splitted the image from the content.Below is the working code for my Question. <?php $output = preg_match_all('/<img.+src=\'"[\'"].*>/i', $post->post_content, $matches); ?> <div class ="single-post-flex-slider"> <ul class="slides"> <?php for($i =0;$i<$output;$i++){ ?> <li> <img src="<?php echo $matches[1][$i]; ?>" width="500px" height="300px" /></li> <?php } ?> </ul> </div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, attachments" }
MobilePress plugin and WordPress 4.1 update A client website is currently running on WordPress 4.0.1 and he asked for an update to 4.1. The website uses the MobilePress plugin, which had problems with WordPress updates in the past, but unfortunately I can't find out much about that. On the MobilePress's official plugin page, it says it's compatible up to WordPress 3.6.1 (though it's working on this 4.0.1 installation). I have some questions: 1. How important is to do the WordPress update? 2. Can I revert the update case something wrong happens? 3. What could eventually break, regarding the MobilePress plugin? And how could it be fixed? **EDIT** Updated, nothing bad happened.
I'm going to be short: 1. Be up to date is very important. There are a lot of reasons but my "favourite" is security. 2. Make a backup before update, so you can restore the site if something was wrong. 3. What can be broken and how could it be fixed? I can not know, I've never used that plugin and I'm not going to test it for you (sorry, test and fix third party software is not the purpose of this site), but I can advise you to do this: make a mirror site with the exact same set of themes and plugins. Working in the mirror site, enable `WP_DEBUG` to know if you are using deprecated stuff that can break WordPress in the future. Fix errors if any. Then update. If everything is fine, you are ready to update the live site.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, updates, mobile" }
Parent and child categories Below is part from a `WP_Query` loop. I have two parent categories ABC and 12, and each has a few child categories. In the first `td` I would like to have the category slug from ABC children and in the second from 12 children. The post may be in one of the two child categories, or both. One from ABC and one from 12, or one from ABC or one from 12. $inCat = get_the_category(get_the_ID()); echo "<td>".(!empty($inCat[0]->slug) ? $inCat[0]->slug : "")."</td>"; echo "<td>".(!empty($inCat[1]->slug) ? $inCat[1]->slug : "")."</td>"; How can this be accomplished?
Have a look at get_the_terms()? <?php // Change 'category' if using a custom taxonomy and not referring to the default blog categories $terms = get_the_terms( $post->ID, 'category' ); ?> <tr> <td><?php foreach($terms as $term) { // show which categorie(s) under ABC if( $term->parent == '0' ) ) { echo $term->name; } } ?></td> <td><?php foreach($terms as $term) { // show which categorie(s) under 12 if( $term->parent == '1' ) ) { echo $term->name; } } ?></td> </tr>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query" }
Remove quicktag buttons but not Visual / Text editor and tabs I wish to remove the quick-tag buttons in the text (html) editor in TinyMCE but not the html editor itself nor the tabs for choosing between the editors. When I use $settings = array('quicktags' => false); wp_editor($input, 'editor_name', $settings); Wordpress removes the entire text editor and the Visual / Text tabs for choosing between the editors (as stated in the codex). I have tried $settings = array('quicktags' => array()); But all buttons remain. Looking through the source code I cannot see a new native remove button code, just add. For backwards compatibility there is listed a `edRemoveTag = function(){},` but I cannot find the actual function itself. I have only found this related thread for quicktags in WP4.0 but it does not seem to cover this issue.
As you noted, setting quicktags to false removes the "visual" and "text" tabs. So, to leave the tabs you need to set quicktags to true and remove the buttons: $settings = array( 'quicktags' => array( 'buttons' => ',' ) ); wp_editor($input, 'editor_name', $settings); To have this in all quicktags instances you can use `quicktags_settings` filter: add_filter('quicktags_settings', 'cyb_quicktags_settings'); function cyb_quicktags_settings( $qtInit ) { //Set to emtpy string, empty array or false won't work. It must be set to "," $qtInit['buttons'] = ','; return $qtInit; } If you are using a plugin that add custom quicktags, you may to set a high priority argument to the filter (later execution): add_filter('quicktags_settings', 'cyb_quicktags_settings', 100);
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "tinymce, wp editor, quicktag" }
Calling the Menu Title within wp_nav_menu array function Been struggling with this for a little while. I want to call a menu but include the title of the menu above the menu list. The basic code I have is as follows - <?php wp_nav_menu( array( 'container' => 'div', 'container_class' => 'rmm-footer', 'theme_location' => 'resources' )); ?> This produces a list as follows - Menu Item 1 Menu Item 2 Menu Item 3 But I want it to go as follows - TITLE Menu Item 1 Menu Item 2 Menu Item 3 Anyone got any ideas? Thanks in advance.
You can not get the menu title using `wp_nav_menu()`, you need to get the menu object as follow: //Change with the ID of your menu $menu_ID = 5; $nav_menu = wp_get_nav_menu_object( $menu_ID ); // then echo the name of the menu echo $nav_menu->name; With the above code, you can insert the menu name in `wp_nav_menu()` using `items_wrap` parameter. For example: $menu_ID = 5; $nav_menu = wp_get_nav_menu_object( $menu_ID ); wp_nav_menu( array( 'theme_location' => 'resources', 'container' => 'div', 'container_class' => 'rmm-footer', 'items_wrap' => '<ul><li id="item-id">'.$nav_menu->name.'</li>%3$s</ul>' ) );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 6, "tags": "menus" }
How to use custom previous/next link ? I have this : <?php the_posts_pagination( array( 'prev_text' => __( 'Previous page', 'twentyfifteen' ), 'next_text' => __( 'Next page', 'twentyfifteen' ), ) ); ?> Which gives this output : !enter image description here What I want is this : !enter image description here How to do this using the_posts_pagination() please ?
Do this to output only links for previous and next pages: <?php previous_posts_link ( 'Previous' ) ?> <?php next_posts_link ( 'Next' ); ?> Then add filters to your functions.php to add a class to each link: function next_posts_link_css ( $content ) { return 'class="next"'; } add_filter( 'next_posts_link_attributes', 'next_posts_link_css' ); function previous_posts_link_css ( $content ) { return 'class="prev"'; } add_filter( 'previous_posts_link_attributes', 'previous_posts_link_css' ); Then style the `.next` and `.prev` links using CSS.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pagination, html" }
Insert plugin content before body end How do I make plugin's content appear in a place I want? For example let's say I have a plugin that output's a paragraph: echo "<p>foo<p>" If I do this it will appear on a page outside the DOM. How to make it append for example just before the end of body using PHP?
Hook the `wp_footer` action to output markup before `</body>`: function your_function() { echo '<p>foo</p>'; } add_action('wp_footer', 'your_function');
stackexchange-wordpress
{ "answer_score": 9, "question_score": 3, "tags": "plugins, php" }
Change location of header.php and footer.php I wish to organize the my themes directory a little more. Is it possible to move `header.php` and `footer.php` to a sub directory? I guess it's done by hooking on to some action, but is it possible with just a config setting?
It is not possible to override header/footer via hooks in respective `get_header()`/`get_header()` functions. However it is often overlooked that these function allow input and loading _different_ headers. For example `get_header( 'nested/header' );` will look for `header-nested/header.php` in theme's folder. It's kind of a hack in regards to subdirectory use, but it works. :)
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "templates, directory, footer, custom header" }
Custom post type templating problem I have a custom post type named 'product', with taxonomies 'brand' and 'type'. I'd like to have Archive Page A: * sidebar with all the 'brand' terms linking to their respective archive page * list of all the products that belong to the term. I'd like to have Archive Page B: * sidebar with all the 'type' terms linking to their respective archive page * list of all the products that belong to the term. When I click on a permalink of a product on Archive Page A, it should direct me to Single Page A * sidebar with all the 'brand' terms linking to their respective archive page * content of the product And similarly when I click on a product link on Archive Page B, it should direct me to Single Page B * sidebar with all the 'type' terms linking to their respective archive page * content of the product How do I achieve this result in WordPress?
Archive pages A & B already exist as your brand and type term archives, you can style those differently by creating `taxonomy-brand.php` and `taxonomy-type.php` templates. The remaining piece is two different single product views. The simplest way to achieve that would be to append a GET var onto the permalinks: WordPress has the built in function `add_query_arg` to help add that for you: echo add_query_arg( 'origin', 'brand', get_permalink() ); Then in your single post template you can check the value of `$_GET['origin']` to determine what to display in the sidebar.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, custom taxonomy, custom post type archives, advanced taxonomy queries, template hierarchy" }
Add action on delete comments? I add some input fields to the comment form, and than this new data is stored on commentmeta table. When a comment is deleted, the data on commentmeta is still there. How can I delete these data when a comment is deleted? (I need an action similar to the delete_post but for comments...does it exists?)
Look at the function `wp_delete_comment()`. It fires an action before the comment is deleted: /** * Fires immediately before a comment is deleted from the database. * * @since 1.2.0 * * @param int $comment_id The comment ID. */ do_action( 'delete_comment', $comment_id ); … and one after deletion: /** * Fires immediately after a comment is deleted from the database. * * @since 2.9.0 * * @param int $comment_id The comment ID. */ do_action( 'deleted_comment', $comment_id ); So you can bind your callback to that: add_action( 'deleted_comment', function( $comment_id ) { delete_comment_meta( $comment_id, 'your_meta_key' ); } );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "comments, database" }
Add action to fire when a published post is updated I have a couple of actions setup: add_action('publish_post', array($this, 'newPost'), 10, 2); add_action('post_updated', array($this, 'updatePost'), 10, 3); When I update an already published post the 'newPost' method is fired as opposed to the 'updatePost' method. I imagine this is because the post is already published so what would be a good way to fire a different method (or be able to identify that it's an update as opposed to a newly published post) when a previously published post is updated?
As an alternative, you can make use of the 'transition_post_status' hook for this. This hook is fired whenever a post's status is changed. In your case, you need to check whether the old and new status of the post is the same, which is `publish` You can also set conditionals according to `$post`, which is the current post being updated/published etc. You can try the following: add_action('transition_post_status', function ($new_status, $old_status, $post) { if ( $old_status == 'publish' && $new_status == 'publish' ) { //Do something when post is updated } }, 10, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, plugin development, actions" }
Load specific js & css based on class or ID? I noticed that there are many tutorials on how to load specific JS & CSS for a specific page. The problem I have is that sometimes my plug-ins load on specific posts and specific pages. I cannot have rules to define these pages or posts. Is there a way to load specific JS & CSS based on class or ID? For example, I am using Next-Gen Gallery plugin. I want to program such that my site only loads Next-Gen' JS and CSS only when it sees this ID in the page (ngg-album). If possible, can I use wildcard, like if the page see any ID or class starting with NGG*, load Next-Gen JS & CSS. Thanks! Cliff
WordPress enqueues javascript before the HTML is rendered so WordPress doesn't know what the class or ID is on the page. What you MIGHT be able to do is deenqueue the Next-Gen gallery Javascript so it isn't loaded at all and then create your own Javascript file which loads the required Next-Gen JS if a particular class or ID is found. have a look at the jQuery function `getScript()` <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, page specific settings" }
Update status of all posts in a category For one of my project I just want to change the post status of all the posts inside a specific category from publish to pending. It is possible to change status of multiple posts at once? I want to use this functionality in a custom theme I am developing. thanks
I am sure there's an easier way to accomplish this, but this how I would've done. 1. Query all posts with category X and status X 2. Update query results with status Y. $target_category = 'news'; $change_status_from = 'draft'; $change_status_to = 'publish'; $update_query = new WP_Query(array('post_status'=>$change_status_from, 'category_name'=>$target_category, 'posts_per_page'=>-1)); if($update_query->have_posts()){ while($update_query->have_posts()){ $update_query->the_post(); wp_update_post(array('ID'=>$post->ID, 'post_status'=>$change_status_to)); } } You can place this code inside a page template, or in functions.php. It's likely that you only need to run it every now and then. So I would create a template for it. Add it to the template and then assign that template to a specific page that's maybe marked as private or draft.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, themes, publish, post status" }
add custom option to get_categories dropdown I have a dropdown menu for selecting categories in a widget that I am working on. Everything is working and options are being saved in the database. What I am trying to do now is add a blank option instead of it being automatically set when you click save. In this situation, the user might not want to set a category. $this->categories = get_categories(); foreach ( $this->categories as $cat ) { $selected = ( $cat->term_id == esc_attr( $category ) ) ? ' selected = "selected" ' : ''; $option = '<option '.$selected .'value="' . $cat->term_id; $option = $option .'">'; $option = $option .$cat->name; $option = $option .'</option>'; echo $option; } How can I append a blank option to the select?
I presume there is an open option html element before that code provided. After that select tag is opened and before you run through that loop echo out a blank option with value=""
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, dropdown" }
has_post_thumbnail() Returns False on Scheduled Posts I am making some changes to a custom WP template and have hit an odd issue. Published posts work absolutely fine, but when you view a scheduled post the Featured Image disappears. It's as if there was no featured image at all and `has_post_thumbnail()` returns false. Here's the relevant piece of code I'm working with, relatively simple stuff really: while (have_posts()) : the_post(); if (has_post_thumbnail($post->ID)) { $featuredImage = wp_get_attachment_url(get_post_thumbnail_id($post->ID)); } } And again, this works fine on published posts but as soon as I set the date to the future the image stops coming through. It seems strange that images would be treated differently based on the publish date, is there anything which WP changes on scheduled posts vs live posts which could be causing this?
Well it turns out that the reason `has_post_thumbnail()` was failing was because `get_post_meta()` was returning empty for scheduled posts. I'm still not sure why, but in case someone else has the issue, my workaround was to create a new function to fetch the featured image ID without relying on `get_post_meta()`: function get_featured_image_id($postID) { global $wpdb; $data = $wpdb->get_results($wpdb->prepare("SELECT meta_value FROM wp_postmeta WHERE post_id = %d AND meta_key = '_thumbnail_id'", $postID)); if (!empty($data[0]->meta_value)) { return $data[0]->meta_value; } } Then you can get a featured image URL in your template with the following line: wp_get_attachment_url(get_featured_image_id($post->ID))
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, post thumbnails, scheduled posts" }
Stuck on my server root folder, robots.txt file not deleting I remove robots.txt file in my server root but google can't delete that. Webmastertool to create robotx.txt file How can I remove or disable.
WordPress generate a dynamic robots.txt which does not physically exists. To remove/disable it you have two options: **Option 1** : Remove `do_robots` action in your theme functions.php or plugin remove_action('do_robots', 'do_robots'); The action `do_robots` is still available to be added again by other plugins. **Option 2** : Create a real robots.txt file, put it the root folder of your site. This will stop WordPress (or plugins) auto generate its own.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "robots.txt" }
Wpdb query for comment meta for current post I have a comment meta field that displays a rating for each comment, I was wondering if there is any way I can query the database to get the sum total of these ratings for each post. I have included the following code in my `single.php`, but it obviously gives the total from all the comments. Is there anyway I can alter it to include only comments from the current post. // set the meta_key to the appropriate custom field meta key $meta_key = 'rating_total'; $ratingtotals = $wpdb->get_var( $wpdb->prepare( " SELECT sum(meta_value) FROM $wpdb->commentmeta WHERE meta_key = %s ", $meta_key ) );
You can join to the comments table and use `get_the_ID()`: // set the meta_key to the appropriate custom field meta key $meta_key = 'rating_total'; $ratingtotals = $wpdb->get_var( $wpdb->prepare( " SELECT sum(cm.meta_value) FROM $wpdb->commentmeta AS cm JOIN $wpdb->comments AS c ON (c.comment_ID = cm.comment_id) WHERE cm.meta_key = %s AND c.comment_post_ID = %d ", $meta_key, get_the_ID() ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "wpdb, comment meta" }
Gravity Forms Upload each entry to Unique Folders When someone uses my form, they can upload upto 15 images. I have about 10 - 20 uploads a day, which means that i could get upto 150-300 images per day. The issue i've got is with where these images are stored. ALl in the /uploads/ folder without any reference to who uploaded them. Is it possible to move these uploads into a unique folder, named after the entryID of the submitted form, maybe with another field name, so: `../uploads/gravity/[firstname]_[entryID]/[uploads here]` If this is possible, then I can use an FTP client to access each entry & all the relevent files with ease, without needing to log into wordpress and click through each entry. ### Note: I'm also using Zapier at the moment to take these files & put them in their own folder, but this is costing me month fee because there are so many entries. If I can do it all on my own site, this would be fantastic.
Here's some code that will get you at least half way there: < Changes you'll need to make: 1. Also stash the current `$entry` object in the `stash_current_field_id()` method. 2. Use the stashed `$entry` to modify the file upload path in the `modify_file_upload()` method.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "plugin gravity forms" }
Page title not showing up I have this in my header.php file -> <title><?php is_front_page() ? bloginfo('description') : wp_title(''); ?> - <?php bloginfo('name'); ?></title> This shows title in my browser window for all pages except one. I looked from my admin panel under the Pages section, if there are something missing, but did not find anything(or did not know where to look). Where should I look to solve this problem and what should I edit?
to show the page title for the page set as the 'blog' or 'posts page', you need to add some code, maybe via a filter on `wp_title()`; example: add_filter( 'wp_title', 'wpse_174379_show_posts_page_wp_title' ); function wpse_174379_show_posts_page_wp_title( $title ) { if( get_option( 'page_for_posts' ) ) { $posts_page = get_post( get_option( 'page_for_posts') ); $title = ' ' . $posts_page->post_title . ' '; } return $title; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "pages, title, wp title" }
How can I detect a chosen Isotope layout option from within Javascript to generate appropriate layout? I am trying to make a custom gallery post where a user may select Isotope layout modes (masonry, packery etc.). I don't want to create a custom template for each layout mode and then get it depending on whether a post includes a certain layout option. It seems that this solution will require a lot of duplicate code. Is it possible to access the chosen post option from within a javascript file to generate a corresponding layout. May be some AJAX request to the appropriate PHP variable that holds this post option will do? If yes, how to implement this? Thanks
The established technique of passing data to JavaScript in WordPress is `wp_localize_script()`. Despite the name it's widely used for arbitrary data, outside of localization purposes. So it is certainly possible to retrieve the necessary data and pass it to the script in this way.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, theme development, gallery" }
Filter string like a slug I have a WordPress site using pretty permalinks. I want to filter a string to that the it ends up with the exact same formatting as the url slug, does anyone know the filter or function to do so?
You can use `sanitize_title()` function: $string = "This is title string"; // return "this-is-title-string" $slug = sanitize_title( $string ); You can also filter the result of `sanitize_title()` function using `sanitize_title` filter: add_filter( 'sanitize_title' , 'sanitize_filter_callback', 10, 3 ); function sanitize_filter_callback( $title, $raw_title, $context ) { // do something }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "permalinks, slug, formatting, sanitization" }
Set homepage to only display posts from one tag I'd like my homepage to only display posts from a single tag. Is this possible? If yes, please advise. For instance, > www.mysite.com/tag/sometag will only display posts with the `sometag` tag, but how do I get www.mysite.com to automatically display only the posts seen on > www.mysite.com/tag/sometag page?
You should use `pre_get_posts` to alter the main query on the home page. With the proper conditional tags and parameters (check `WP_Query` for available parameters) you can achieve what you need You can do the following to just display posts from a given tag on your homepage add_action( 'pre_get_posts', function ( $query ) { if ( !is_admin() && $query->is_home() && $query->is_main_query() ) { $query->set( 'tag', 'SLUG_OF_TAG' ); } });
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "tags, homepage" }
How to get all users that uploaded avatars or have gravatars? Is there a way to get all users that: 1) uploaded an avatar or 2) have a Gravatar? I want to filter users that doesn't meet one of these conditions. **UPDATE** I forget to mention that this is for Buddypress. Anyway, I found an answer for the first condition, this is the `bp_get_user_has_avatar()` function that checks if a given user ID has an uploaded avatar. Now I need only a Gravatar validation for the second condition.
This function `bp_get_user_has_avatar()` calls `bp_core_fetch_avatar` with this argument `'no_grav' => true` so you could write your own function to see if a user is not using the default avatar: function lurie_avatar_check( $user_id ) { $retval = false; if ( bp_core_fetch_avatar( array( 'item_id' => $user_id, 'no_grav' => false, 'html' => false ) ) != bp_core_avatar_default( 'local' ) ) $retval = true; return $retval; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "buddypress, avatar, gravatar" }
Stop Wordpress appending `-2` to the end of my url after i change it When i try to set the url of a page in wordpress (4.2) it keeps apending `-2` to the end of the url, i guess its becuase this ulr already exists, but i checked and it dosnt, although at one time it did but that page has since been deleted. Any idea how i can use the url i want and get it to stop apending `-2` ? This is what im seeing the wp-admin dashboard when trying to change the url : The edit box : !edit box wp-admin url Once i click OK : !once i click ok on changing the url
I know this topic is old, but I was having the same issue, and none of the suggested fixes worked. I didn't have any pages still in trash. I didn't have a category with the same name as my page. I didn't have another page with the same name. So I did something crazy. WP was trying to name my page as page-2, so I went to mywebsite.com/page to see what happened. A page with a single photo popped up. I had a PHOTO with the same name as the page, and WP media manager gives photos permalinks based on the file name! Fix was to rename the photo (still keeping SEO in mind), and using the permalink editor for the page. TAH DAH! Like magic, it worked
stackexchange-wordpress
{ "answer_score": 28, "question_score": 15, "tags": "permalinks, urls" }
add_editor_style not working I created a style sheet > editor-style.css I want to load this css file using add_editor_style() function, In my functions.php function my_theme_add_editor_styles() { add_editor_style( 'css/editor-style.css' ); } add_action( 'after_setup_theme', 'my_theme_add_editor_styles' ); I also tried this solution add_editor_style is not loading in frontend. Any solution?
You shouldn't need an action to add an editor style. Simple add the following anywhere in your functions.php: add_editor_style('css/editor-style.css');
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "theme development" }
How to query custom post type one after another I am trying to query my custom post types. I can display both of them with this code: `'post_type'=> array('map','item')` But I don't want them to mix. I want "map" to display before "item". Please help!
Since version 4.0 is available `'type'` option for `'orderby'` argument in `WP_Query`. Also, thanks to the more powerful ORDER BY in WordPress 4.0 you can control how posts of a post type are ordered. Example (untested): $q = new WP_Query(array( 'post_type' => array('map','item'), 'orderby' => array( 'type' => 'DESC', 'title' => 'ASC' ) ));
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "query" }
How to get order of posts? How can I get the order through which the query is done? For example, my woocommerce product archive page is querying by ordering according to the order_by select box (as seen below). How can I get what my posts are ordered by? For example, if it's default sorting, I want to know. If it's by popularity, I want to know. If it's by newness, I want to know. !enter image description here
Found the answer from the WordPress docs. For what the query is ordered by, I use: global $wp_query; echo $wp_query->get('orderby'); For the order by which the posts are queried: global $wp_query; echo $wp_query->get('order');
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "wp query, loop, order, sort" }
How to call a custom taxonomy term name inside a function? With the following function, the content of another page is included into a page template, which is working fine: // add content of another page function show_post($path) { $post = get_page_by_path($path); $content = apply_filters('the_content', $post->post_content); echo $content; } The function is called like this: Now I placed this code inside a custom taxonomy template: * taxonomy-$taxonomy-$term.php Is there a possibility, to give the $term-name automatically in this function, without hard-coding it? For example, the custom taxonomy template is taxonomy-cars-mercedes.php, I want the function doing this: <?php show_post('mercedes'); // Shows the content of the "About" page. ?>
You can get the current term slug from the global query. You could do something like this: if( is_tax('cars') ) { //We are in "cars" taxonomy archive page, now get the queried term $term = get_query_var( 'term' ); show_post($term); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, functions, terms" }
Can I change my language to English? I created my account and first blog while waiting at the airport in Switzerland. Now my admin page and blog are in German! I can't understand what most of it means, so I can't seem to be able to switch it back to English. Please help? Thank you!
Go to **Einstellungen/Allgemein/Sprache der Seite** (`wp-admin/options-general.php`) and select **English**. Then click the Button **Änderungen übernehmen**. !enter image description here
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "language" }
Will placing custom templates in sub directory break any native WordPress functionality I have, on an existing project, created a folder named `templates` in the theme root directory where I have put all my custom template files, all the files that have the `Template Name: BlahBlahBlah` in the top of the file. This change broke places in the code where I had done this to get the file name: `get_post_meta( $post_id, '_wp_page_template', true );`. I fixed it like this: `basename(get_post_meta( $post_id, '_wp_page_template', true ));`. My question is if I broke something in WordPress by doing this change. Does anyone know?
Since WP 3.4 page templates can be stored in theme root folder or direct sub-directoryr, that is no problem. But rename page templates, which include moving files to other directories, will unassign that page templates for all pages currently using it. To reassign the page template, simply edit the page, and reselect the desired template. About the `get_post_meta( $post_id, '_wp_page_template', true );`, if the template file is under "mytheme/sub-dir/templae-file.php", the `_wp_page_template` value should be "sub-dir/template-fie.php". Using `basename` leave only "template-fie.php"; you may have reasons to need only the name of the file but it is not the correct value for `_wp_page_template`, so it is not broken.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, page template, directory" }
How to maintain wordpress site blogs in production and staging? I work as a website admin in my company. We are selling digital products using WooCommerce. We wanted to have staging and production in order to avoid any site down. So in staging we use to create blogs from our blog team and then we'll push it to production. The problem is when any post is created in staging say it has a ID 586 then in the mean if an order is made in production then its ID also 586. Since WooCommerce order is also a Post, I cannot push site either from production to staging or staging to production to have both Because the POST ID will should be unique. Is staging and production maintenance are only for **Development Purpose**? If it is only for Development Purpose then how can i manage my blogs? Because my blog team members some time breaks the sites. How should I limit them and have a good running site. Should i have separate site for Shop but this may affect SEO. Any advice would be helpful
What you have does indeed sound more like production and development. General practice it that between these two the data only goes from production to development, but never the other way. Having true staging, you can push the data from to production, is challenging precisely for the reasons you describe. There are solutions around, but even those on commercial and pricey side don't quite promise reliable two-way synchronization with live environment. The low hanging fruit for you would be to find and eliminate those ways in which your content authors can break the site. Their roles and permissions should be locked down and there should be procedure for content going live, rather than authors just pushing publish.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin, blog, woocommerce offtopic, subdomains, maintenance" }
Blog search just returns to front page (not search results!) When I enter in a search query in my blog's search box, it simply returns to my blog's front page with URL < Here's my search box code: <form method="get" id="searchform" action="<?php esc_url( home_url( '/' ) ); ?>"> <?php echo "<!--[if !IE]> --><input type='text' name='s id='s' class='blog_search_field' placeholder='Search' value=''/><!--<![endif]-->"; echo "<!--[if IE]><input type='text' name='s id='s' class='blog_search_field' value='Search' /><![endif]-->"; ?> </form> The front page is a static page at www.mywebpage.com, and then the blog index page is at www.mywebpage.com/?page_id=7. Any pointers would be terrific. Thanks for reading!
I think that your problem is a syntax error: `name='s` should be `name='s'`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "search" }
add function to saving change on Options Pages i make page like this link and it work fine but i need to run some script after it like editing a file i was add it to function my_function() { //do something } function register_mysettings() { //register our settings register_setting( 'baw-settings-group', 'new_option_name' ); register_setting( 'baw-settings-group', 'some_other_option' ); register_setting( 'baw-settings-group', 'option_etc' ); my_function(); } add_action( 'admin_init', 'register_mysettings' ); but it load every time (without submit!) please help. thx
To execute a task after a option has been updated, you can use `updated_option` action hook: add_action( 'updated_option', 'updated_option_callback', 10, 3 ); function updated_option_callback( $option, $old_value, $value ) { //Do something } Also, you can use `update_option_{option-name}` specifically for each option. For example: add_action( 'update_option_new_option_name', 'update_new_option_name_callback', 10, 2 ); function update_new_option_name_callback( $old_value, $value ) { //Do something }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, forms, admin menu, options" }
TinyMCE Javascript URL Question ed.windowManager.open({ file : url + '/shortcode_generator_popup.php', I would like to move this file one folder above the current one that it's in. I'm wondering how I can rewrite this so that is points to the folder above. I've tried: file : url + '../shortcode_generator_popup.php' but of course it only turns into: /includes/js../shortcode_generator_popup.php Thanks for any help!
I think the best way is to use the before_wp_tiny_mce() hook. Then, you can define the url in PHP; and pass it to the page so it is available to TinyMCE. function sgp_before_wp_tiny_mce() { ?> <script type="text/javscript"> var sgp_plugin_url = "<?php echo plugins_url('shortcode_generator_popup.php', __FILE__); ?>"; </script> <?php } add_action('before_wp_tiny_mce', 'sgp_before_wp_tiny_mce'); You may need to change the plugins_url() to match the appropriate location of your php file. Then, you can use the variable in your plugin tinymce script to get the location. ed.windowManager.open({ file : sgp_plugin_url, I haven't tested this... it's from memory. Let me know if you encounter any issues and I'll adjust accordingly.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, urls, tinymce" }
Is it possible to dynamically register menus? I have a template, lets call it `menu.php`, which contains a menu. I would like the user to set the menu on this page by using WordPress's own menus, so I don't have to create something custom for it. They can in theory have multiple `menu.php` pages. The page template has a custom meta box which saves a menu slug to the database. When the page loads, I was hoping to be able to load this slug and set the current menu by using this slug. The problem is that since I set the slug dynamically, I don't know how to register the menu. I thought maybe I could register the menu when I saved the the slug to the database, but that didn't quite work out. Any ideas?
Register a menu is really register a menu location, but I think you don't need to register locations so you can avoid the register step. I think what you need is `wp_nav_menu( )` function. For example, in the page template: //Get the menu slug stored in page custom meta field //Replace menu_meta_field_name with the correct name of the meta field $menu_slug = get_post_meta( get_queried_object_id(), 'menu_meta_field_name', true); wp_nav_menu( array( 'menu' => $menu_slug ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, metabox" }
Iterate through ID's in loop I have created a custom loop based on category, now I would like to run a function with the specific ID of the current post being iterated through as a parameter. I have.. $secondary_loop = new WP_Query(array( 'category_name' => get_the_title(), 'posts_per_page' => 5 )); while ( $secondary_loop->have_posts() ) : $secondary_loop->the_post(); $post_ids = wp_list_pluck( $secondary_loop->posts, 'ID' ); $current_id = array_pop($post_ids); rating($current_id); the_title(); the_content(); endwhile; wp_reset_postdata(); However, with the code above only the 1st array element of `$post_ids` is used. How can I pass the current ID to `rating()`?
You can access the current post ID within the loop via `get_the_ID()` while ( $secondary_loop->have_posts() ) : $secondary_loop->the_post(); rating( get_the_ID() ); endwhile; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, loop, array" }
WP_User_Query users by registered date I'm trying to get the number of user who registered today. I've tried this: $args = array ( 'role' => 'Subscriber', 'meta_query' => array( array( 'key' => 'user_registered', 'value' => '2015-01-13 00:00:00', 'compare' => '>=', 'type' => 'DATE', //also tried DATETIME, TIME ), ), ); $user_query = new WP_User_Query( $args ); $user_query->total_users; But the results is always 0. This works: global $wpdb; $results = $wpdb->get_results( "SELECT * FROM `wp_users` WHERE `user_registered` >= '2015-01-13 00:00:00'"); echo count($results); But shouldn't WP_User_Query() be able to do this. Am I doing something wrong with the args?
You can simply use the `date_query` parameter on the user registration date: $args = array ( 'role' => 'subscriber', 'date_query' => array( array( 'after' => '2010-01-13 00:00:00', 'inclusive' => true, ), ), ); $user_query = new WP_User_Query( $args ); This part of the `WP_User_Query` source code, makes it possible: // Date queries are allowed for the user_registered field. if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) { $date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' ); $this->query_where .= $date_query->get_sql(); }
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "wp user query" }
WP Sql query multiple where clause I'm trying to get the users that have registered after a specific time (this case $today) and who have the newsletter field true and the account false. This is what I have so far but the result is always 0. $new_users_newsletter = $wpdb->get_results( "SELECT * FROM $wpdb->users RIGHT JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id WHERE ($wpdb->users.user_registered >= '$today' AND $wpdb->usermeta.meta_key LIKE 'newsletter' AND $wpdb->usermeta.meta_value LIKE 'true' AND $wpdb->usermeta.meta_key LIKE 'account' AND $wpdb->usermeta.meta_value LIKE 'false') GROUP BY $wpdb->users.ID" );
You can try this with `WP_User_Query` instead: $args = array ( 'meta_query' => array( array( 'key' => 'newsletter', 'value' => 'true', ), array( 'key' => 'account', 'value' => 'false', ), ), 'date_query' => array( array( 'after' => '2015-01-13 00:00:00', 'inclusive' => true, ), ), ); $user_query = new WP_User_Query( $args ); where I assume your user meta values are _boolean_ strings, i.e. `'true'` and `'false'`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wpdb, sql" }
Get uri of CPT archive page I have a custom post type which uses an archive page and a slug 'rewrite' => array('slug' => 'news'), 'has_archive' => true I am using a PHP form on one page which I want to post to `/news/` each time. I want a proper way to return the uri of this archive page `(www.mysite.com/news/)` from other pages. I don't mind doing round about manipulation to get the 'news' sub-string, I just want to eliminate 'magic variables' in my code.
You would use the `get_post_type_archive_link` function. As you declined to provide the name of your post type ( but you did provide its URL slug ), I cannot provide a full example, however, it would be something similar to this: $link = get_post_type_archive_link( $post_type ); echo '<a href="'.$link.'">View Archive</a>';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Some comment box wordpress in 1 post Can I add more sections to comment on the same post? For example, I have an Entry and it has 4 tabs, In every tab you need a comments section, Is this possible? Thanks
Yes it is possible but not exactly trivial or well documented. The easiest option is to have different comment types (ie, have new ones in addition to the traditional comment, pingback and tracback). The biggest problem with this approach is that most of wordpress API and admin is not built to be flexible enough to sopprt different comments types, for example the recent comments widget might show all type or only one, and it might be hard to style them based on type. But yes, that design is totally possible just requires more work and some dipper digging into the comments related apis.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, comments, metabox" }
using same mysql user with many databases As we know that in order to connect **WP** with database we should to define **mysql username** and password in wp-config.php, so at that point i have a question regarding security or ( some sort of connecting error ): > **it is good practice using same mysql user with many databases** one thing is that i haven't seen any trouble regarding this but was thinking someday it will come :) hope you understand well thanks in advance
Well it's really not good practise, but this depends on how you're accessing the other databases. For example, I have a server that hosts 10+ different Wordpress sites. I have two options for connecting to the databases: 1. Use the _root_ login in all my wp-config.php files as it's easier 2. Create a user and logins associated with each database for each site Number 1 is useful when I'm developing _locally_ /on a virtual machine as the databases aren't accessible to the outside world. Number 2 is definitely the best practise when you're running a _live server_ with multiple databases. At most if your password does get compromised you're only exposing one database.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, mysql, wpdb" }
Remove h1 from 2015 theme I'm a Wordpress newbie! I have two h1 when I list my site categories using a URL of the following format: > < I get a HTML page with a header of Category: <h1>.... then another h1 with my post title. How can I remove the first h1? Things I've tried: 1. I found the offending CSS using Inspect Element. I have created a child theme with the following code: .page-header { display: none; } This removes the extra h1, but the extra h1 tag is still visible when I view the page source
Edit the according _template file_ out of the Template Hierarchy, so in your case the template regarding the Category Display.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, themes, child theme" }
Why does the Full-width Template in Twenty Twelve pack so many classes into the body class attribute? I created a page and selected the "Full-width Page Template, No Sidebar" option in the Twenty-Twelve Theme. The viewed page has the following body tag: <body class="page page-id-2 page-template page-template-page-templates page-template-full-width page-template-page-templatesfull-width-php logged-in admin-bar full-width custom-font-enabled single-author customize-support"> I want to create a child theme with a custom full width page, but I am not sure why I would need to include so many similar classes, or what the best practice would be for creating them. Most of them do not appear to actually be used in styling the page. For example, I can't see the use for page-template-page-templatesfull-width-php. Perhaps it is a bug.
Those classes are output by the `body_class` function, which can be filtered by plugins to add their own classes. You don't need to (and shouldn't) harcode classes into the body tag in your template, just add that function within the body tag: <body <?php body_class(); ?>>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "templates, child theme, theme twenty twelve" }
How to add text to the start of all comments? For example somebody replies- Hi! This is a Comment! but is published as Text- Hi! This is a Comment! Any ideas folks? I'm totally stumped. I want to add the extra text so it appears within the comment rather than before/around it in the theme.
You can try the `comment_text` filter: /** * Prepend text to each comment content. */ add_filter( 'comment_text', function( $comment_text ) { $text = 'Some text'; return $text . $comment_text; }); if you're displaying the comment text with: <?php comment_text(); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, comments" }
NoFollow Entire Website By default whenever you disable indexing via Admin Settings > [ x ] Discourage search engines from indexing this site It adds a meta tag in the header like so: <meta name='robots' content='noindex,follow' /> How do I change that to be `nofollow` instead of `follow`? I find it odd it enables "follow" and overall want it `noindex,nofollow`. I could echo directly into `wp_head` but this doesn't account for pages such as wp-login and the likes.
Thought this was a great question so I went digging. In default-filters.php on line 208 there's `add_action('wp_head', 'noindex', 1);` as of WordPress 4.1. The noindex() function in turn checks to see if you have set blog_public option to 0. If you have, it calls wp_no_robots() which is simply: function wp_no_robots() { echo "<meta name='robots' content='noindex,follow' />\n"; } Neither of last methods are filterable, but a simple plugin will do the trick to remove the hook: /* * Declare plugin stuff here */ remove_action('wp_head','noindex',1); Now, you're free to hook your own action on to echo out what you want. add_action('wp_head', 'my_no_follow', 1); function my_no_follow() { if ( '0' == get_option('blog_public') ) { echo "<meta name='robots' content='noindex,nofollow' />\n"; } }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 6, "tags": "seo, robots.txt, nofollow, noindex" }
getting post data in functions.php I have done this before but it doesn't seem to be working in this case. I am trying to get the category ID from the supplied slug and then add a metabox to the page if the page id matches the category id. My site is throwing me two errors in the admin area Undefined index: post and undefined index post_id add_action('admin_init', 'add_meta_boxes', 1); function add_meta_boxes() { global $post; $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ; $cat = get_category_by_slug('audio'); $id = $cat->term_id; if ($post_id == $id) { add_meta_box( 'repeatable-fields', 'Audio Playlist', 'repeatable_meta_box_display', 'post', 'normal', 'high'); } }
I got it to work by doing it this way if (is_admin() ){ $post_id = isset($_GET['post']) ? $_GET['post'] : isset($_POST['post_ID']) ; if( $post_id && in_category('audio', $post_id) ){ add_action('admin_init', 'add_meta_boxes', 1); } } The only problem with this method is that it won't display the metabox until after you have published the post. The $post_id variable shows bool(false) until you publish. so the big problem is that when you go to make a new post, there is no category ID to get. So using the link posted to Toscho's post, you can add category information and use $_GET to test for that information. Looks like it gets populated when you tick the category for that post.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories" }
Hide the_meta if no value I would like to have post-data associated to posts and displayed on my blog. I added to single.php (as seen here: < and all the metadata is displayed as intended, however I'd like the whole div to be hidden when no metadata is entered in any field. How can I do that? I'm running Wordpress 4.1. Thanks
You can check if there is any meta for the current post by using `get_post_meta` So to hide/show the div you would wrap your code in an `if` statement like this... <?php if( get_post_meta(get_the_ID()) ) { ?> <div> <?php the_meta(); ?> </div> <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta" }
How to include a JS file in this theme? This makes the Jquery script work in a plugin: `wp_enqueue_script('metabox_js', plugins_url('add_meta_box/js/metabox.js',dirname(__FILE__) ), array('jquery'));` I have been trying for ages, & this doesn't make the script work in a theme (have put this in functions.php): function prefix_enqueue_scripts3() { wp_enqueue_script( 'metabox_js', get_stylesheet_directory_uri() . '/js/metabox.js', array( 'jquery' ), '1.0.0', true ); } add_action( 'wp_enqueue_scripts','prefix_enqueue_scripts3'); Please can someone advise. I have another Jquery file further up functions.php, which uses Jquery successfully, I have only changed the file location and file name with this one. Please can someone advise? Thank-you!
From `wp_enqueue_scripts` action: > `wp_enqueue_scripts` is the proper hook to use when enqueuing items that are meant to appear **on the front end**. For admin-facing scripts, the correct action hook is `admin_enqueue_scripts` function prefix_enqueue_scripts3() { wp_enqueue_script( 'metabox_js', get_stylesheet_directory_uri() . '/js/metabox.js', array( 'jquery' ), '1.0.0', true ); } add_action( 'admin_enqueue_scripts', 'prefix_enqueue_scripts3' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp enqueue script" }
How to query if meta_key does exist or not? Good day, I am trying to negate my query to show all instead except for a post with a custom field of file gallery. 'meta_query' => array( array('key' => 'file_gallery', 'value' => '1', 'compare' => '!=') ) because not all of my post does have this key, and my query seems to work only for those post that has "file_gallery" field with the value of 0 or no 1. thanks :)
Adding a `NOT EXISTS` clause should force `LEFT JOIN`s: 'meta_query' => array( 'relation' => 'OR', array('key' => 'file_gallery', 'value' => '1', 'compare' => '!='), array('key' => 'file_gallery', 'compare' => 'NOT EXISTS'), ),
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, terms" }
Admin Panel - Disable Moving Selected Terms To Top of Metabox By default whenever you select a category it moved it to the top of the term list, which in most cases it pretty user friendly. I want to disable this featured and leave my term list in the default order no matter what is selected. The reason I want this is because i have a script running that relies on `<ul class="children">` to be available, but if a term is selected it removes it from this format and to the top of the list. I've search around but wasn't using the correct keywords to pull anything useful. I'm sure I need to do something with the `Walker_Category_Checklist` Walker but walkers are very much a mystery to me. I'll be playing around with that and some WordPress files to find how what function is pushing it to the top but in the meantime I figured if anybody has a solution on-hand: **How do I disable WordPress pushing selected terms to the top of the Post Category Metabox?**
Try adding this in your functions.php file: // Let's stop WordPress re-ordering my categories/taxonomies when I select them function stop_reordering_my_categories($args) { $args['checked_ontop'] = false; return $args; } // Let's initiate it by hooking into the Terms Checklist arguments with our function above add_filter('wp_terms_checklist_args','stop_reordering_my_categories');
stackexchange-wordpress
{ "answer_score": 8, "question_score": 3, "tags": "categories, metabox, taxonomy, walker" }
What is the difference between these two custom queries? Could you please explain what the difference is between the following two custom queries? $arguments = array ( 'post_type' => 'post', 'meta_key' => '_count-views_all', 'orderby' => 'meta_value', 'tax_query' => array( array ( 'taxonomy' => 'category', 'field' => 'slug', 'term' => 'student-success-stories', ), ), ); and $arguments = array ( 'post_type' => 'post', 'meta_key' => '_count-views_all', 'orderby' => 'meta_value', 'category_name' => 'student-success-stories', ); The first query does not return any results on my website while the second works as desired. I was convinced that they shoudl be doing the same thing. Apparently this is not the case.
It is `terms` (plural) not `term` (singular) in tax query arguments. :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query" }
Add custom class to existing menu items from custom meta I would like to add a custom class to my existing menu items. The problem is, that I would like to do something like this: <li class="<?php echo get_post_meta($post->ID, "_icon", true); ?>">...</li> <li class="<?php echo get_post_meta($post->ID, "_icon", true); ?>">...</li> <li class="<?php echo get_post_meta($post->ID, "_icon", true); ?>">...</li> or <li><a class="<?php echo get_post_meta($post->ID, "_icon", true); ?>">...</a></li> So I have a custom meta tags for posts and pages and they supposed to be a classes of li or a elements. I know that I have to use custom walker, and I found this article, but I dont know how to add custom meta tags to $item_output and this example adds new menu. Greetings
I've got the filter just for you: `nav_menu_css_class` function wpse_175057_nav_menu_css_class( $classes, $item ) { if ( $item->type === 'post_type' && $class = get_post_meta( $item->object_id, '_icon', true ) ) $classes[] = $class; return $classes; } add_filter( 'nav_menu_css_class', 'wpse_175057_nav_menu_css_class', 10, 2 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, menus, pages, walker, post meta" }
Accessing loop functions (e.g the_title or the_content) from post ID I have an array of post IDs obtained through complicated filtering code. I want to display posts from these IDs, and for each post I need access to regular post functions like the_title and such. More importantly, for each post I need to retrieve custom fields values (and even more precisely I need values of "relationship" fields created with Advanced Custom Fields plugin). Is there a way to access regular post functions from anywhere simply based on post IDs, just as if I was inside the regular loop?
You can make use of `get_post` to get the post objects of a given post. This will be unfiltered objects, so you would want to make use of `apply_filters` and the appropriate filters described in the linked page. If you need to get info from a custom field, whether native custom fields of ACF fields, you can simply add the ID to the `get_post_meta` for native custom fields or `the_field` or `get_field` functions in ACF. Remember, by default, the post ID of the current post is used, but you can change this to any post ID you wish to get info from
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom field, loop" }
Extract image url associated to a category I found a function that allows me to attach a category to an image in media uploader function add_categories_to_attachments() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init' , 'add_categories_to_attachments' ); I'd like to be able to, when I'm in the category I assigned the image to, get the url of the image. I just need to find out how to extract the info about the image associated with that category. I should be able to do that via taxonomies, but I don't know how to achieve that. EDIT: I forgot to add that I'm working outside of the loop, I need to show this image in the breadcrumbs of the category view.
I found what I needed: $category = get_category( get_query_var( 'cat' ) ); $cat_id = $category->cat_ID; $images = get_posts( array('post_type' => 'attachment', 'category__in' => $cat_id)); if ( !empty($images) ) { foreach ( $images as $image ) { $image_url = $image->guid; } } else{ $image_url = ''; } First I got the category, and current category ID I'm in. Then in `$images` I got the attachment that's attached to this category. Then I just listed them (I used `print_r` to see all the array values fro $images) and found the url (I need the url of the image to set the background image in the breadcrumbs). You can get the image directly by using `wp_get_attachment_image($image->ID)`, but I need the url so I'm using this. Oh and I'm avoiding the plugin usage, since I'm building a theme, and I'd like everything to be available from the theme itself. Hope this helps someone :)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, images" }
Woocommerce - Check product stock availability from external database I have an external database (not a Wordpress one) where my client's stock is managed and I need to check the product availability considering this database, not the wordpress' one. My inicial idea is to find where the product is parsed from the database and make an external query to the other database, filling whatever field is to be filled with the product quantity on stock and theoretically all the other validations would work as if this value was the one set on the wordpress database. Is this the best approach to the problem? If so, is there a hook/filter where I can attach my code? Which one? Thank you all in advance
Your approach is impractical in any site with decent traffic. In that case having real time updates from a DB is the best way to bring your site down. What you need is to check the availability when people at items to carts and then again before the actual checkout. In addition you can update the current number of items every hour (or faster if you really want to try to be as accurate as possible) with a wordpress cron task, but this number is just to give the user a feeling if he should hurry and buy or he has time to think about it. Just remember that unless you are going to keep some ajax going to update the number, the user will very likely see a stale information as the kids called him (or any other distraction) and he returned only after half an hour later to look at the product.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, woocommerce offtopic" }
Custom Posts on Different Pages So first off let me start off saying I'm new to WordPress development. I know HTML/CSS/JS like the back of my hand, but PHP and it's functions are new. Anyway. My problem may be simple, so here goes: I'm working with a client who has several pages. He has a blog page and a testimonial page that both use posts. I've managed to get the WP Dashboard to show a tab to add the custom post (Posts, Speaking, Press, and GiveFirst pictured below). Now I need to get just these posts to appear on the specific page (i.e. Speaking posts go to example.com/speaking and Press goes to example.com/press). ![]( My research has only led me to figuring out that I can create custom-post-types. Now I just need to know where to go from there. Any help or redirection would be appreciated! P.S. I also can't get custom fields to work...so if anyone can guide me there that'd be awesome. But lower priority for now.
Make sure that the Custom Post Type is public. Then create a page with the same name (slug). That shall do. To customize them make sure the CPT has an archive, then create archive templates such as archive-press.php, archive-speaking.php.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts, pages" }
Registration form labels - add asterisk Is there an easy way to add a required symbol like '*' _after_ the html `<label>` text content in the default user registration form? I'd like the Username and E-mail labels to display: Username * and Email * I've tried using CSS, as in: `#registerform p label::after { content:" *"; color: red; }` But the asterisk appears _under_ the text field, not beside the text. I checked the Codex but couldn't find a WP filter, so does this mean I need to create an entirely custom registration form?
The * appears under the field because the field is inside the label. There doesn't appear to be any useful filters for this, but you could use one of the hooks to inject some JS on the page that adds the *: required = jQuery( "<span>*</span>" ); required.css("color", "red"); jQuery('label br').before( required ); Note: if you're going to use a library like jQuery in my example, you'll need to queue that as well - it's not by default on the register page
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "forms, user registration" }
pre_get_posts or $where, which one to use? i have a custom search widget, that is searching only one custom post type that contain a meta_key that is greater than or equal to 1, in which i am gathering post_id. of all of those post_id(s), i am wanting to exclude those that have meta_key '_start_date' (stored like 01-16-2015) with value >= 'search_input_start_date' AND meta_key '_end_date' (stored like 01-16-2015) with value <= 'search_input_end_date'. my question is: should I be using the action 'pre_get_posts' and the above as $args, or should I be using the filter 'posts_where' and directly going to the $wpdb ?
In _general_ this would make sense at `pre_get_posts` since you could just express conditions as meta query and let WP figure out SQL. In your _specific_ case this won't work, since that format is horrible for programmatic comparison. Unless you can change format to something more friendly, you will probably _have_ to write some pretty custom SQL to make it work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, wpdb, pre get posts, posts where" }
Remove wp-login link from auto generated wordpress's email Am trying to edit the text inside the auto generated email wordpress send to the users when they are trying to register. The specific email has a link to wp-login which i don't want. Is there any plugin or code to modify? Any help is appreciate
Your code does not work, so i decided after some failed codes i found to use my mind and add 301 redirection
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "user registration" }
Including Custom Template on template_include Filter not working I have registered a template like this, but on the template, I was wondering how to get all of the current themes functionality to exist on the template, as some parts are missing in the way I have this template set up. the template file is currently blank, I included wp_head() and get_header() in the template file, it works somewhat, but most of the theme is missing, such as the pages content. any ideas? <?php add_filter( 'template_include', 'template_management' ); if ( ! function_exists( 'template_management' ) ) { function template_management( $template ) { return plugin_dir_path( __FILE__ ) . 'templates/the-template.php'; return $template; } } ?>
I would suggest you copy `page.php` into your custom template, and then modify the code as required. At the very least, your template should look something like: <?php get_header() ?> <?php while ( have_posts() ) : the_post() ?> <article <?php post_class() ?>> <?php the_title( '<h1 class="entry-title">', '</h1>' ) ?> <div class="entry-content"> <?php the_content() ?> </div> </article> <?php endwhile ?> <?php get_footer() ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates" }
Featured image not showing on page I am new to creating a theme and wonder if anyone can help? I am trying to display all the featured images from posts under a specific category (id=5) on my index page and it's not working using the following code: <?php $myblogPosts = new WP_Query('cat=5'); // Cat 5 is the blog category. if ($myblogPosts->have_posts()) : while ($myblogPosts->have_posts()) : $myblogPosts->the_post(); ?> <div class="hero_img"><?php the_post_thumbnail(); ?></div> <!--Post image--> <?php endwhile; else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> Can anyone see why it's not working? All I get is the "Sorry, no posts" displayed where the image should be. BTW, I got the cat id from this URL ( Thanks in advance!!
From the url you supplied it looks like you are using a custom post type of **blog**. The most likely reasons you are not seeing the post you want to display is that by default `WP_Query` is only set to display posts - see WordPress Codex on WP_Query Post & Page Parameters for more info. So for your WP_Query to return the post you are after you will need to replace line 2: $myblogPosts = new WP_Query('cat=5'); // Cat 5 is the blog category. With something more like this: $args = array( 'post_type' => 'blog', 'cat'=> 5); // Cat 5 is the blog category. $myblogPosts = new WP_Query($args);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, post thumbnails" }
Creating other page than page.php I want to load other page than page.php. I mean following situation: Always when I click position from menu it is starting page.php. I want to special position in menu sutch that it load my.php (which will be similar to page.php)
Wordpress allows you to create custom page templates. Create your own template and assign that template to any page you like in the WordPress admin ;)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Uninstall languages Hosting installed WordPress with like a gazillion languages. Can I just remove the language .mo and .po's for the languages I don't want or will that break something unintended?
Yes, you can delete the .mo and .po files without any negative effect, but they don't cause any harm by just being there.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "language" }
How can I globally italicize certain text? I have a large WordPress site, and I want to take a certain text phrase and italicize all instances of that phrase, for all pages. Does anyone know of a plugin that can do this? Particularly, for the sake of clarity, my site works like this: We have a bunch of different plant species, and of their names consist of "R.", space, and a word. An example is _R. Sanctum_. So I'd like to figure out how to use code to search all the pages for instances of _R. (any-text-word)_ , and italicize those found instances. I picture regex being used, but I'm eager to hear all ideas.
Add this into your functions.php file. This is untested, but should work :) add_filter( 'the_content', 'italicize_latin_names' ); function italicize_latin_names( $content ) { // Split up the content into an array of single words $words = explode( ' ', $content ); // Loop through each of those words foreach( $words as $key => $value ){ // If a word equals 'R.', add an <i> before it, and a </i> after the following word if($words[$key] == 'R.' ){ $words[$key] = '<i>' + $pieces[$key]; $words[$key+1] = $words[$key+1] + '</i>'; } } // Put all of the pieces back together return implode( '', $words ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, regex" }
Installed in root, want second in subdirectory ## Current situation I am trying to plan ahead and avoid any grievous pitfalls and/or headaches in adding a second domain/site for a client. 1. WP is currently installed in root 2. The client wants a second site created for a new brand that **_may_** end up as it's own entity, so **separate** public facing **domains**. 3. The root site already has almost 200 pages + posts 4. I'd like to keep a central user base if possible. 5. They have quite a few plugins running 6. I use IWP, so keeping track of updates and backups really isn't that difficult. ## Question(s) 1. Is it possible to create a subdir install with a separate domain pointing at it (with out moving the first install to it's own subdir)? 2. Would it be more beneficial to convert to a multisite install instead?
It can be done, I did it here for example: < \- dev site with seperate wordpress install < \- main site on root level. I set everything up at my host, I'd recommend you just contact them first and be sure you can have separate database installs as that's basically all you need.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, directory, installation" }
wordpress blog posts's time I want to show the blog posts'time like below: "A heading title , posted by XYZ, 1 hour ago" I want the time that says: 5 minutes ago, 1 hour ago, 2 days ago 1 month ago like that. how can i get this working? i can't get the exact wordpress API code to implement it. Please help.
In your template where you see `the_title()`, you will want to change it to something along the following: echo get_the_title() . ', ' . 'posted by ' . get_the_author() . ', ' . human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) . ' ago'; `human_time_diff()` is the one doing the part regarding your topic. Though you also asked for the others. However, if you want it to look even cleaner, try: printf( '<h2>%s, posted by %s, %s ago</h2>', get_the_title(), get_the_author(), human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) ); Replacing whatever tag/formatting you want in the first parameter
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "date time, blog page" }
Editing WordPress comments : generating comment from selection On my website, I would like users to comment using a list, which will then generate a comment for the user. For example, the comments section will have a multi-select box asking " _which part of the article did you like?_ ". The select box will list the sub headings of the article. After the user submits their selection I will have php function to generate the comment saying " **User X** liked the **introduction** and **Conclusion** ". I have searched Google, but results only show how to change the look of the comments cosmetically. Can anyone provide tutorials/pages/filters/hooks that will help in this situation? Apologies for the lack of detail in the title. I could not find the best way to describe.
Three aspects to this: 1. Adding the checkboxes to the comment form 2. Adding the values from the checkboxes to the comment meta data 3. Displaying the values of the checkboxes 1. Assuming you want to dynamically generate these based on the headings in the article, you'll need to parse the post content for headings and add the checkboxes to the comment form. This could be done via JS or PHP, depending on your preference. If you're going to go with PHP you may want to make use of Transients so that you're not parsing the content on every page load. 2. You can use the `comment_post` action hook, which is fired right after the comment itself has been added to the database, to check `$_POST` for the checkbox fields added in 1 above and then add these as comment meta using `add_comment_meta`. 3. Number of ways to do this depending on your preference. I would recommend first trying the `get_comment_text` filter to add the values from the meta data.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments" }
Redirect User to login page Well I am newbie to WP and the question may sound duplicate but even after trying for few days I can not make this work. I have integrated a custom login and registration form in my WP site which is different form usual WP login and register forms. I need to perform the following actions 1. Redirect user to login page if directly accessed any Page URL 2. Redirect user to home page if directly accessed login/register URL. For redirecting user to home page if tries to access login/register URL after being already logged in, I have used below code function checkUser(){ $user = wp_get_current_user(); if ( empty( $user->ID ) ) return false; return true; } function __construct(){ add_action('init', array($this, 'checkUser')); } Even if I use `wp_redirect(site_url());exit;`; that do not seem to work and it goes into infinite loop. Thanks.
Here is from my previous project. The function is hooked into the `template_redirect` action. Inside the function there are 2 conditionals. The first is the the one that will redirect logged in user _away from_ the login page. And the other one is to redirect non logged in user _to_ the login page. // add a redirect for logged out user add_action('template_redirect', 'redirect_user'); function redirect_user(){ global $current_user; if (is_page('login-page-for-non-logged-in-user') && is_user_logged_in()){ $return_url = get_bloginfo('url'); wp_redirect($return_url); } // this part is untested if (!is_page('login-page-for-non-logged-in-user') && !is_user_logged_in()){ $return_url = get_bloginfo('url'); wp_redirect($return_url); } // end of untested part }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, login, wp redirect, user registration" }
How to List All Custom Post Types Names (Not Posts) Having Some Custom Post Types Like `"Projects", "Products"` and `"Events"` I need to list them in a page. Please be advis that I do not want to list any POST here! instead I just want query the name of all Custom post type and Link them into `archive-projects.php`, `archive-products.php` and `archive-events.php` for each of them. Can you please let me know how to do that? Thanks
Get all custom post types: $post_types = get_post_types( array ( '_builtin' => FALSE ), 'objects' ); Sort them by their name: uasort( $post_types, 'sort_cpts_by_label' ); /** * Sort post types by their display label. * * @param object $cpt1 * @param object $cpt2 * @return int */ function sort_cpts_by_label( $cpt1, $cpt2 ) { return strcasecmp( $cpt1->labels->name, $cpt2->labels->name ); } Link the post type names to their archives if archives are actually available: foreach ( $post_types as $post_type => $properties ) { if ( $properties->has_archive ) { printf( '<a href="%1$s">%2$s</a><br>', get_post_type_archive_link( $post_type ), $properties->labels->name ); } }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "custom post types, custom post type archives" }
Images are not shown I can see my images in media/libary but not in posts. The issue seems to be that the REAL url to the image ends with image.jpg (if I go to this url I can see the image). But in the post I get the "broken image link"-icon. And when I check the image url it ends with image-sizeXsize.jpg, so Wordpress for some reason adds sizeXsize (example 1000x1000). How do I solve this? Edit1: I have just installed WP. Have tried the theams twenty eleven and twenty fifteen, same problem. I have installed alot of plugins, will take a look at those. Edit2: I have deactivaded all plugins, still same problem. Latest WP version.
It seems that there is problem with your image thumbnail. May be it doesn't exists. You can fix this by instaling Regenerate thumbnails plugin. Then generate thumbnails for all media files. Another way is to include image in post or page with full url. You can do this by selecting image size to "Full Size" in `Attachment Display Settings` in media uploader popup box. !enter image description here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Edit post meta direct from post.php? Does anyone know of an easy way to be able to edit ALL of a single post's meta at once ie on the `post.php` `&action=edit` page? As some of the meta has been put in there with the `update_post_meta()` and isn't consistent between posts it would be really helpful to have a way of just editing ANY meta value from the post's edit page? Have been scouring around for anything, code / plugins and can't see it mentioned much but thought it must be a common enough problem? I've attached an image of my imagined solution from a meta inspector edited through the browser inspector just in case it isn't clear what I'm asking !Screenshot
So awkwardly realised I'd been going about this whole thing in a stupid roundabout way and in fact Milo above in the comments is completely right, and proves that the codex still has secrets for everyone, or maybe just me. The eureka (or durr-eka) moment came after reading this post here about setting up and editing the content of the metaboxes. Instead of calling the individual meta to be edited using `get_post_meta` I used the `get_post_custom()` and simply cycled through every post meta entry using a `foreach` loop and a simple `isset` form for each generated. Apologies for the obvious question but thought I'd answer it myself rather than delete it in case anyone else out there is doing it wrong too.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts, metabox, post meta" }
Authors in menu, template list post by author Can i get a specific author in main menu and when you click on it to see all the post buy this author. Also i need to see all posts ordered by authors too in the menu. In what template should it build, because it is not a category.
By default, you can view posts by authors with a URL of the form `{home_url}/author/{author-slug}/` If you'll be writing any PHP and need to output a link to an author's posts, see the function get_author_posts_url. **Edit:** If you'll be writing your own author post page template, the filename should be one of the following formats: `author-{nicename}.php`, `author-{id}.php`, or `author.php`. The templates override in the order I listed them -- last one being the fallback.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "posts, categories, author" }
Passing user defined variable into get_permalink I'm trying to use a predefined variable (generated from an earlier sweep of the database) in wordpress' standard get_permalink( get_page_by_title) function. I'm assuming that this is possible? But I can't get it working, it always returns the url of the current page. For the sake of clarity below I'm just manually assigning the variable. Code... <?php $mypagename = "My First Page"; ?> <a href="<?php echo esc_url( get_permalink( get_page_by_title( $mypagename ) ) ); ?>">LINK</a> N.B - My First Page (my-first-page) does exist in the database Any ideas where I'm going wrong or if it's not possible to do it like this do you have any other suggestions? Many thanks!
`get_page_by_title()` returns a object by default and `get_permalink()` needs the ID as first parameter. Try: $mypagename = "My First Page"; $permalink = get_permalink( get_page_by_title( $mypagename )->ID );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, variables" }
How can i call a custom method on submission of a custom plugin post type? I have registered a custom post type .On submission of that page/ post can i call a custom method . How ? Can i add a method in plugin file and will it call on post type submission by ACF or any other way in the admin side?
save_post is an action triggered whenever a post or page is created or updated, which could be from an import, post/page edit form, xmlrpc, or post by email. The data for the post is stored in $_POST, $_GET or the global $post_data, depending on how the post was edited. For example, quick edits use $_POST. Since this action is triggered right after the post has been saved, you can easily access this post object by using get_post($post_id) <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, functions, callbacks" }
Changing custom post type URL issue I have this function and it does just what I need, it replace words in URL perfectly, but links don't work. All links are good and display on site well structured, as I wanted, but just don't open posts. Is there any way that I can make it work? add_filter('post_type_link', 'replace_link', 1, 3); function replace_link( $link, $post = 0 ){ if ( $post->post_type == 'item' ){ return home_url('food/'. $post->ID); } else { return $link; } } function custom_rewrite_rule() { add_rewrite_rule('^food/([^/]*)/?','?item=$matches[1]','top'); } add_action('init', 'custom_rewrite_rule', 10, 0); `
Your `post_type_link` uses the post's ID, but the `item` query var expects a postname. To query by ID you need to use the `p` query var and set `post_type`: add_rewrite_rule('food/([^/]+)/?$','index.php?post_type=item&p=$matches[1]','top');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, urls" }
Child theme - Overriding 'require_once' in functions.php I am attempting to modify a wordpress theme with a child theme. My parent theme has the following function in its functions.php: require_once(get_template_directory() . "/includes/theme-styles.php"); I would like to change this to include my own stylesheet: something like: require_once(get_template_directory() . "../child-theme/includes/theme-styles.php"); I can include this function in my child theme's functions.php, but because the child theme's functions.php is loaded first, I see no way to override/prevent the parent theme's require_once() from being called. Is there any way to do this, or a possible workaround? Thanks
You can use `get_stylesheet_directory()` to refer to your child theme, then you can point to your file. require_once( get_stylesheet_directory() . '/includes/theme-styles.php' ); It will load your file and replace the parent theme file.
stackexchange-wordpress
{ "answer_score": 18, "question_score": 10, "tags": "functions, themes, child theme, parent theme" }
Help with sorting and storing data on Wordpress I want to implement something where users can log in and review products and search for products to see reviews. I want to store multiple attributes to allow for really refined searches. I need things to be very sortable. Ideally, I would connect custom MYSQL databases on my server to Wordpress. I also want to load pictures, etc for the products. I expect there would be thousands of products added. I'm stuck on how I would get the products/ reviews to display. Is there currently a plugin that handles this type of thing? Is this even feasible through Wordpress and should I spend time trying to create a plugin to do this for me? Is it possible with a new page type? Or would I run into trouble trying to create thousands of pages.
Why do you want to go for a custom MYSQL database altogether? You can simply use custom post types for products. Please check < You can add images, custom fields such as review, ratings etc. There are many plugins that can help you create custom post types easily. < < There is another plugin you can use to create a products catalog. Check this: < Thanks, Faizan
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, mysql" }
How to get category id's which are added in main menu? I called post categories in my main menu using menu section and set them as child menu items now when I click that category menu items I need to make parent menu item active.I know doing this with jQuery for pages in this way <?php if(is_page( 842 ) || is_page( 846 ) || is_page( 844 ) || is_page( 848 ) || is_page( 'current-tenders' )){?> <script type="text/javascript"> jQuery( window ).click(function() { jQuery('li.menu-item-28').addClass('tendersactive'); alert('hi'); }); </script> <?php }?> in `is_page( ID )` here ID is page id but how to do in this same way for categories or is there any other way to achieve this?
Unfortunately `is_category()` not worked for me but if(in_category( 'articles' )) `in_category()` worked Codex reference for in_category().
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, menus" }
Register `product_cat` taxonomy for default post post type Is it possible to register WooCommerc's `product_cat` taxonomy for use by posts? I have tried the following with no success. function custom_cross_content_type_taxonomies(){ register_taxonomy_for_object_type( 'product_cat', 'post' ); } add_action( 'init', 'custom_cross_content_type_taxonomies', 0); I will be writing posts about each of the product categories and it would be nice to group with the same terms without duplicating the taxonomy. Appreciate your suggestions
I'm not familiar with woocommerce, but in general, taxonomies are registered via the init hook with a priority of `1` or default priority which is `10` Your code is fine, so I suspect that your priority is wrong here. In short, you are trying to add the taxonomy to the post type before the taxonomy even exists. Try adding a priority of `11` or higher. This would ensure that the taxonomy is registered before you try to assign it to a specific post type
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, taxonomy" }
Which banner plugin is this? Which plugin is the main banner on this demo website ? I've wasted much time looking for it. I just couldn't find it. <
That would be revslider < Warning, last year there was some information about it having a vulnerability on wordpress websites. The 2 websites I had it pre installed on via themes have also broken due to a update in rev slider requiring me to go in and amend the rev slider code to disable it. I was unable to get in the admin section otherwise.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -6, "tags": "plugins, sidebar" }
How does wordpress name resized image copies? I've noticed that usually, Wordpress will name a scaled image copy by appending the resolution, like this: `image1-200x200.jpg` Is this _always_ the case? Are there any special circumstances where they would be named differently? I ask because I have seen a few named after the image size name, like this: `image1-large.jpg` I'm trying to come up with a simple regex to only show original images, so I'd like to know what rules Wordpress follows when naming these files. Can anyone enlighten me?
yes, the naming convention for resized images is name-{width}x{height}.extension. Is it good enough info to base a regex on? in practice most likely yes, but in theory no. You just can't know if mark-20x20.jpg was not simply uploaded that way, and even in places where you know that a resized image should be used you have no way to know if wordpress had decided that the best fitting image is the original. The proper way to know what is the original image based on image url is to search the attachments part of the DB for it which can be a little PITA (no simple API for it as far as I know).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, uploads" }
Custom meta Title for custom post type archive from page I've set up some custom post types, and created custom archives, eg in the following format: archive-books.php (With a template name of "Books Template"). I then have a page (/books/) created in wordpress, with the above archive-books.php assigned as the template. How would I get the the meta title (wp_title) to be the title that I set on the page (/books/)? - At the moment it's just showing "books | sitename". Even if I change the All in One SEO custom title. I am using All in One SEO plugin also, but that doesn't seem to work. What I THINK is happening, is that it's just ignoring the page and jumping directly to the archive-books.php as it matches the Wordpress custom post type naming rule?
Well I felt I better update this old question, the SEO plugin by Yoast now allows assigning of all SEO abilities to custom post type archives. So that's the best solution.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, title, custom post type archives, plugin all in one seo" }
How to open up comments to all visitors The "Leave a Reply" section at the bottom of my pages is asking for a login before visitors can comment. Is there any way I can turn this off so anybody can leave a comment?
Go to yoursite... /wp-admin/options-discussion.php Is `Users must be registered and logged in to comment` selected? If so, unselect it and `Save Changes`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments" }
Multisite - create a category in specific site I have a multisite I want to create a category but in a specific site. I used this functions below: wp_create_category('mycategory', 0); but this will create a category on the main site. I keep searching if there will be a built in function in wordpress to create a category in a specific site but it seems there is not. Is there any easy way to create a category in a specific site?
What you need is switch_to_blog and maybe get_blog_id_from_url which you would use like this: $blog_id = get_blog_id_from_url( 'www.example.com' ); switch_to_blog( $blog_id ); wp_create_category( 'mycategory', 0 ); restore_current_blog();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "categories, multisite" }
What is the best way mark entries as featured? In quite a few wordpress projects I have a request in which Projects (or other post type) have to be **featured in the Portfolio page** (or other listing page) instead of the default date sorting lists. Usually i create a checkbox as a custom field, but then it is not easy to know what projects are marked in the admin edit page. Creating a category would also be a solution, but I am not sure if it is a good practice to deliver a theme with predefined categories. I also read about creating a _archived_ post status, so that only 'published' entries would then be featured. So, what do you think is the best way to achieve this?
OK, after reading Rarst post i went with the _taxonomy term_ option. It was very simple: 1. Just after the register_taxonomy call, i added one line of code `wp_insert_term('Featured','filter');` being filter my taxonomy. 2. Then I modified the query in the template, adding the line `'filter' => 'Featured',` inside the args. Now I only see the featured projects in the portfolio page, which was my main goal. Moreover, i can easily list the featured projects in the backend, as well as Quick-edit this option. **UPDATE** : As a side note, if you then wanted to list the categories without the _Featured_ category: 3. Exclude the term by id: `<?php $featured_term = get_term_by('name', 'Featured', 'filter'); $featured_id = $featured_term->term_id; $args = array('taxonomy' => 'filter', 'exclude'=>$featured_id); wp_list_categories($args); ?>`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme development, featured post" }
Fixed version number for cached stylesheets and javascript Unless i use: wp_enqueue_style( 'dazzling-style', get_template_directory_uri() . '/css/main.css?ver=', array(), rand(10,99999), 'all' ); Then everytime I visit my site, be it local or live, I see that the version is 4.1 and even though I upload a new stylesheet or js, the browser still sees that 4.1 version. What's going on? Where is that 4.1 coming from?
4.1 is coming from your WordPress version. Also you should not append `ver=` to the src manually but use the fourth parameter of wp_enqueue_style.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "cache" }
List all Custom Post Type posts excluding certain Taxnomy term I'm writing a theme in which I've registered "Services" as Custom Post Type that supports "Type of Service" Custom Taxonomy. I want to list all the posts of type "Services" except those which have "Featured" as "Type of Service" term set. I can write code to list the Posts that are under specific Taxonomy term; but how to write wp_query that will exclude posts from certain Custom Taxonomy term? Waiting for your reply... Cheers, \r
Sounds like you're looking for the `NOT IN` value of the `operator` argument of a `tax_query`. Depending on your situation, you should use either `WP_Query` or `pre_get_posts`. Your tax_query would then look something like this: 'tax_query' => array( array( 'taxonomy' => '{your taxonomy slug}', 'field' => 'slug', 'terms' => 'featured', 'operator' => 'NOT IN' ) )
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, wp query, custom taxonomy, loop" }
Trying to create an edit page link? Using a plugin and have created a page that offers more fields in a spreadsheet format. To add these extra fields you simply click edit on the row you want to edit.... Now when I am in the plugins template and want create a link to the edit link for that particular post type I keep getting one data for one level down the loop. In my specific example I have url: xyz.com/learning/project/test-product <?php global $post; echo $post->post_name; print_r(get_defined_vars());?> The post name I get is "project". But when dumping my variables I see [post_name] => test-product. Edit: Later on down the variable list I see [post_name] => project. So obviously I am capturing the later instance. How do I capture the first instance?
What you want is the `get_edit_post_link` function. Usage: echo '<a href="'.get_edit_post_link( $post_id ).'">edit</a>'; Your use of `global $post` and the other issue is a separate problem, you should ask a new question and provide more details ( including the code for the template being used )
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "variables, quick edit" }
How to display checked posts on another page over AJAX? (like comparasion style) I wanted to create an "comparasion" model for my WordPress Website, but gone bad at that. I cannot figure out how to ... On one page I have displayed post (custom post type, ex. "Products"). Next to the title of the post (product) is an checkbox. If user has checked for example two posts/products (ex. product a and product b), how to retrive the value (the $post->ID) of each checkbox or over ? How to save that checked $post->ID of product a and product b for later use in AJAX? Should I retrive them over jQuery .click() function? And last, after click on link or button, how to parse and display those two selected posts (ex. title and content) on separate page, over AJAX? Is that possible? Short version: User checks two posts, hits the button and those checked posts are displayed on another page. Any help would be appreciated! Regards
1. Add `data-post_id` attribute to checkbox and fill it with corresponding post ID. 2. On click on `compare` button (link) retrieve all post ids from checked checkboxes with JavaScript (jQuery) 3. Redirect to the comparision page with post IDs in url as GET parameters. This is just one scenario how your task could be done. PS your question is not related to WordPress itself but is form field of web application architecture.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, jquery, ajax, comparison" }
Possibility of creating a folder in the wordpress root install and installing a file there, all via plugin? Here is my situation. I'm creating a plugin, which uses a 3rd party API service. If I include the file ajaxAPI.php in the plugin itself, then call it via jQuery ajax with the full url, such as < I get a 403 error. I realize it's my server config, but other users may have the same issue. My work around is to create a folder in the site root, place my ajax file there, and call it at that point. There will be sensitive data passed via API, so I don't want to host the ajax file on my own server, for the end users security. Summary: How can I make ajax calls when the plugins directory returns a 403 error?
Use **WordPress Ajax API** for any kind of ajax related stuff. For more details : <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, ajax" }
My RSS feed is not working I run my website on wordpress 4.1 and my website feed is not working. Feed page shows this error message. (This page contains the following errors: error on line 399 at column 105: Input is not proper UTF-8, indicate encoding ! Bytes: 0x1F 0x6F 0x72 0x64 Below is a rendering of the page up to the first error.) I tried it using different theme but still showing same error. Any idea how can I fix this. Here is the feed addresses: < < Thanks
I think it was caused by a plugin please disable all plugins and try again. If it doesn't help try removing following line from "180 power words for writing emotional headlines:" "So it is always a good idea to make emotional headlines for your content."
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "feed" }
Locked out of admin panel after installing HC Custom WP-Admin URL I installed "HC Custom WP-Admin URL" plugin (< on my WordPress installation, and then changed the admin slug value to a cryptic url (< so that the default (< is not visible. Unfortunately now, for some reason, I am unable to unable to see either of the URLs. Effectively, I am now locked out of the CP. I have full access to the database via the hosting provider's cpanel and phpmyadmin. Any way that I can come out of this situation?
you sad u have access to phpmyadmin. Go to it, find `wp_options` table Look for `custom_wpadmin_slug` in option_name and in `option_value` column will be your's custom defined `wp-admin` slug If you'll still wount be able to access then remove next lines in `.htaccess`: <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^{your_wp_admin_slug}/?$ {your_site.com/}wp-login.php [QSA,L] </IfModule> Note that `{your_wp_admin_slug}` is equal to one in `wp_options` table
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, url rewriting, wp admin" }
How to set custom upload directory per user after moving content directory I set the content and the wordpress directory of wordpress like described in the codex: define('WP_SITEURL', ' . $_SERVER['SERVER_NAME'] . '/wordpress'); define('WP_CONTENT_DIR', dirname(__FILE__) . '/content'); Now what I want to do is set an individual upload directory for every user, like this: wpinstance.org/content/uploads/user-name/here-goes-the-file.jpg I already tried a lot using define( 'UPLOADS', dirname(__FILE__) . '/content/uploads'.$current_user->user_name.'/'); as well as many combinations without `dirname()` and so on. It all turned out to take the files up to `wordpress/…something` and leaving the user name part empty. So how can I achieve this? Any ideas?
With credits to petermolnar via `irc://freenode.net/wordpress` I can answer my own question. The key is to set an `upload-dir` filter in the theme's `functions.php`: function per_user_upload_dir( $original ){ // use the original array for initial setup $modified = $original; // set our own replacements if ( is_user_logged_in() ) { $current_user = wp_get_current_user(); $subdir = $current_user->user_login; $modified['subdir'] = $subdir; $modified['url'] = $original['baseurl'] . '/' . $subdir; $modified['path'] = $original['basedir'] . DIRECTORY_SEPARATOR . $subdir; } return $modified; } add_filter( 'upload_dir', 'per_user_upload_dir');
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "uploads, directory, users" }
Create a file format (csv,json,etc) when save/update a Post I need create a file (any type: json, php, csv, txt) when I create or update a post from WPadmin. The format structure would be: ID, "operation to execute" (new post, update post, delete post), title, field2, field3 Thanks! martin
There are a number of action hooks for Post Status Transitions. They each receive the `$post` object as an argument. You could use these to trigger a function that writes your file to disk using `fopen`. Edit: if you're writing CSV, PHP has a function specifically for that: `fputcsv` (`fopen` still required)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "json, xml" }
Run script after clicking Set Featured Image in Media I would like to run some script to get the featured image's width and height after the user clicked 'Use Featured Image' button and use the data retrieved within the Post Edit screen. Is there such hook available for use in JavaScript? Otherwise, do you have other suggestions to achieve this? Thanks for helping! Edit : If there isn't any hook, I tried using the code below but clicking 'Set Featured Image' wouldn't trigger the event, presumably because it's a modal pop-up? Any ideas? jQuery("#set-post-thumbnail").on("click", function(){ alert('clicked'); jQuery(document).on("click", '.media-button-select', function(){ alert('clicked button'); }) })
I think what you need is (function(){ var featuredImage = wp.media.featuredImage.frame(); featuredImage.on('select', function(){ var attachment = featuredImage.state().get('selection').first().toJSON(); console.log(attachment); }); })(); The `attachment` object should have `height` and `width` properties.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "media, thickbox, media modal" }
Enqueue a css using negative conditional tags I'm building a theme on top of purecss.io. In order to make the grid responsive I need to add this stylesheet. From functions.php function load_css() { wp_enqueue_style ( 'purecss-all-not-ie', ' array( 'purecss' ), null ); wp_style_add_data ( 'purecss-all-not-ie', 'conditional', 'gt IE 8' ); add_action( 'wp_enqueue_scripts', 'load_css' ); and the output is <!--[if gt IE 8]> <link rel='stylesheet' id='purecss-new-ie-css' href=' type='text/css' media='all' /> <![endif]--> however the correct conditional tag should be `<!--[if gt IE 8]><!-->` I've found a couple of discussions here and here but I'm a bit lost as I don't understand what's the proposed solution. What should I do?
The bug's only 4 years old so you wouldn't want to rush them would you?! A workaround is to leave out the `wp_style_add_data()` and use the `'style_loader_tag'` filter: add_filter( 'style_loader_tag', function ( $tag, $handle ) { if ( $handle == 'purecss-all-not-ie' ) { $tag = "<!--[if gt IE 8]><!-->\n" . $tag . "<!--<![endif]-->\n"; } return $tag; }, 10, 2 );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "wp enqueue style" }