INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Removing text + shortcode from all posts
I want to remove certain shortcode and text that I manually placed in all my posts from the start but I really don't want to go through every post and remove it manually if I don't have to.
The shortcode is a for an ad and the text just says advert. I just want to remove it from every post if possible.
Thanks! | Simply follow these steps:
1. Export your database, save a duplicate of it
2. Open the database in a text editor, I use Sublime
3. Search for that [shortcode] and text and remove those (can replace them with a backspace or anything else you want)
4. Save that edited database
5. Create a new database and upload this new data file to it, then link your site to it (I recommend this so you can go back to the original database if something goes wrong) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode"
} |
Non Object Notice Error - How to fix please
No doubt I'm missing something obvious here...
The following code to add a body class to an admin page is producing this error notice:
`Notice: Trying to get property of non-object in /.../box.php on line 103`
How to get rid please. Thanks in advance!
public function admin_body_class($classes) {
global $wpdb, $post;
$screen = get_current_screen();
/* Line 103 */ if ($post->post_parent > 0 ) {
$status = 'child-';
} else {
$status = 'parent-';
}
$classes .= ' ' . $status . $screen->post_type;
return $classes;
} | Replace your code with as mentioned below:
public function admin_body_class($classes) {
global $wpdb, $post;
$screen = get_current_screen();
$status = 'parent-';
if( isset( $post->post_parent ) && $post->post_parent > 0 ) {
$status = 'child-';
}
$classes .= ' ' . $status . $screen->post_type;
return $classes;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "wp admin, errors, body class"
} |
Wordpress taxonomy and archive custom class
I want to add custom class. But archive and custom taxonomy both are executed at the same time. When I want to add class to taxonomy page, the archive class is also added. I understand taxonomy is also one kind archive. But I do not want to add archive class to taxonomy. How can I add only taxonomy class?
My approach to do so
function fotogruf_layout_class(){
if (is_search()) {
echo $search_layout_class;
}
if( (is_post_type_archive('gallery')) || (taxonomy_exists('gallery_category')) ){
echo $gallery_layout_class;
}
if (is_archive()) {
echo $archive_layout_class;
}
}
Search page is working fine. But taxonomy page add class from archive class also . I do not want archive class to be added on taxonomy page. | Add another layer of condition to your `is_archive()` test, so that your archive class is only output when the other two are NOT true:
function fotogruf_layout_class(){
if ( is_search() ) {
echo $search_layout_class;
}
if ( (is_post_type_archive('gallery') ) || ( taxonomy_exists('gallery_category') ) ){
echo $gallery_layout_class;
}
if ( is_archive() ) {
if ( ( !is_post_type_archive('gallery') ) || ( !taxonomy_exists('gallery_category') ) ) {
echo $archive_layout_class;
}
}
}
WP's built in body classes might do this for you automatically if implemented. Maybe not to the level of detail you are looking for, however. < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, filters, actions"
} |
Blog url disappears
I have a blog with a permalink structure: `domain.com/blog-page/category/postname/`. blog-page is a page defined as blogpage via settings.
This works fine so far but the problem is if I am in a category and click on a post the url changes to `domain.com/category/postname`. The blog-page is not displayed anymore.
Yoast is set to keep category, Permalinks is set to `/%category%/%postname%/` and category-base and tag-base are name of blog-page. So why does the blogpage slug disappear when I click on a post.
I don't want to use a plugin. Thank you so much | Because this is how WP is set.
You have set your permalinks structure to `/%category%/%postname%/` so when you click on a post link, you will have that post `/%category%/` and then `/%postname%/`.
I guess you wished to have a structure like `/blog-page/%category%/%postname%/`. well just add this to your permalink settings `/blog-page/%category%/%postname%/`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "permalinks, url rewriting, blog"
} |
Can I trust user input in wp_redirect()?
I'm doing a small plugin that is doing this:
$Path=$_SERVER['REQUEST_URI'];
wp_redirect( ' );
exit;
I think that's safe, even if there's user input (request uri) in the function, anyway it should be equivalent to directly typing old.example.com/malicious_url, right? | You can never trust user input. Always prepare a value that you want use in your own code. Example:
$path = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_URL );
if ( $path )
{
$url = ' . $path;
$url_escaped = esc_url( $url );
$status = 301;
$message = "Moved to <a href='$url_escaped'>$url_escaped</a>.";
wp_redirect( ' $path, $status );
wp_die( $message, 'Moved', $status );
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "wp redirect"
} |
Create Page To Count Comments For Each Post In Wordpress Site
I'm trying to count the number of live comments on each post. I would like to extract them on a custom page like ` and have them output like this:
3
0
12
The spacing between all the posts don't matter quite as much, I just need the two columns with all my posts and number of approved comments.
I have come close to doing this with this post and using `echo get_comment_count( 149 );` but it only uses one post at a time. I would like to extract all the posts.
Thanks for your help. | This is pretty easy to do. Put this code in your **functions.php** file.
The logic is pretty straightforward.
* Get all posts with `get_posts()`.
* Iterate over all post, extract comments count and permalink of current post and
* Print out the results.
.
add_action( 'init', 'get_comments_count' ); // Hook to init, elsewhere or use directly in your code
function get_comments_count() {
$all_posts = get_posts( array( 'numberposts' => -1 ) );
foreach( $all_posts as $current_post ){
$comments_count = get_comment_count( $current_post->ID );
$permalink = get_permalink( $current_post->ID );
printf( '<a href="%s">%s</a> - %s<br>', $permalink, $permalink, $comments_count['total_comments'] );
}
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, functions, pages, comments"
} |
Custom Backend data for map to JSON file?
I want to create a map in the frontend with data that is populated with Point of interests. I want to manage the POI data in the backend but need a generated JSON file from that backend data that talks with the JavaScript in the frontend.
If I wanted to implement it manually, how would I do that? | Use the JSON REST API - < \- It lives as a plugin now but will eventually be part of WP Core - <
To manually output JSON, use a combination of wp-ajax to handle requests and `wp_json_encode()` / `wp_send_json_success` for simple PHP Objects and Arrays. See < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "json, google maps, wp localize script, map"
} |
"options.php" not found
I am making a Wordpress theme with a custom admin page. What I did to make it save the settings was this:
<form method="post" action="options.php">
When I hit the submit button, I got an error message saying that "options.php" was not found. I attempted to change the general settings and it worked. It was just with my settings page.
Thanks!
EDIT: I just found something on the Codex about this. But I have no idea what it means. It is at the "Notes" section. If someone could help that would be great!
My code:< | Like @LupuAndrei said, we lack of details, especially the code where you call you form from.
But I suspect, again like @LupuAndrei said, you might not be calling the `settings_fields`, `do_settings_fields` or `do_settings_sections` correctly.
On the function where you build your form, try something like this
<form method="post" action="options.php">
<table class="form-table">
<?php
settings_fields( 'animated-settings-group' ); // This will output the nonce, action, and option_page fields for a settings page.
do_settings_sections( 'hoogleyboogley_animated' ); // This prints out the actual sections containing the settings fields for the page in parameter
?>
</table>
<?php submit_button(); ?>
</form> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, theme development, themes, wp admin, options"
} |
How to add date range in woocommerce with code
I am using Woocommerce and Woocommerce bookings plugins and I would like to add Date Range with time throught a custom code.
;
but I can't figure out how to do it for the Range because it's dynamic and needs a click of button... Any help is much appreciated, thx. | I just figure out how to do it with a bit of reverse engineering, hopefuly this helps someone :
$availability = array();
$availability[0]['type'] = 'time:range';
$availability[0]['bookable'] = 'yes';
//Default priority
$availability[0]['priority'] = 10;
//case 'time:range'
$availability[0]['from'] = wc_booking_sanitize_time( $hours );
$availability[0]['to'] = wc_booking_sanitize_time( $hours );
$availability[0]['from_date'] = wc_clean( $date );
$availability[0]['to_date'] = wc_clean( $date );
add_post_meta( $product_ID, '_wc_booking_availability', $availability ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "php, woocommerce offtopic"
} |
configuration for child theme
I have some trouble to configure and setup my wordpress child theme.
I buy a themes and when I try to do a child. I think the child function is never trigged also, the override files not work too.
**Tree folder** :
;
I try to use this **function.php** :
 and he is never loaded.
What I do wrong?
Thanks | The name of the file must be **functions.php** in plural form not function.php | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "child theme"
} |
How to show Woocommerce add to cart form for variable product on custom location
Woocommerce wraps the add to cart button inside a form. When the product is a variable product the form contains a drop-down list for product variations.
I am making a custom theme and want to show that form on custom location. Is it possible to print that form outside the loop/On a custom location in a single product page? If yes then how can I accomplish that? | I figured out this.
Adding 'woocommerce_variable_add_to_cart()' function prints the variable product's add to cart form. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -2,
"tags": "woocommerce offtopic"
} |
How to hide some categories in dashboard
Is there a way to hide some categories in the dashboard for some users/roles so they won't appear? It should affect both the dropdown menu in the post list and the category checkbox selector in the post page:
;
function restrict_cat( $args, $taxonomies ){
// Don't run if we are not dealing with categories
if( 'category' != $taxonomies[0] )
return $args;
// The check for the user we want to restrict
// you could use current_user_can( $capability ) or test for a specific role here
if( 1 == get_current_user_id() ){
$args['exclude'] = array(
'cat_id1',
'cat_id2'
);
return $args;
}
return $args;
}
check out < for a list of available args. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, filters, dashboard"
} |
Where to find WordPress API changes for each version released
When I go here to download WordPress - < is there a page either on the web or nested within the folders of the downloaded package that will explain any core code modifications (i.e. new or refactored WordPress API components) within the latest version?
I'm trying to learn what major API changes have been introduced or re modified between WordPress 3 and 4. And now with 4.6 on the way for mid August, how can we prep for API changes to come?
Thanks! | Codex (official WordPress documentation wiki) has a list of WordPress Versions with links to changelogs and release posts for each. Though information in those changelogs can be lacking.
Note that WP doesn’t follow semantic versioning or resemblance of. Every version is a minor one and there are no major versions, so 3.9 was simply followed by 4.0 rather than 3.10. There is no significance to first digit change.
With WP’s extreme commitments to backwards compatibility there isn’t quite established update procedure. It is _assumed_ that anything that worked on older version will continue to do so on a newer one.
Practice falls somewhere on the scale from just upgrading and getting rid of any deprecation notices (if any) to paying up to tens of thousand of dollars for complete code audit in context of upcoming release. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "api, wordpress version, wordpress.org"
} |
How does WP knows which template to use for a page
This website uses WooCommerce. There is a **Shop** menu item that when clicked it displays the product categories of WC. I am trying to figure out how Wordpress knows what to display when visiting this page.
I see there is a page created named **Shop** , which is used to create the menu item. But this page is totally empty and nowhere I can find any clue that connects this page with WooCommerce or anything else.
I am searching everywhere in the admin as well, to see if there is something that sets the Shop's pages URL to be related to the WC product categories template but I don't see anything.
So what is the logic here? How is this supposed to work? How can a totally empty page be linked to a certain template?
Thanks for any insights. | The native logic of template choice is contained in file aptly named `template-loader.php`. It processes the current context and calls respective `get_*_template()` functions, until a match is found.
This process results in what is called Template Hierarchy.
However as it was pointed out this only covers native core logic. Plugins can wildly customize this process at different stages or skip it altogether. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -3,
"tags": "menus, pages, page template, woocommerce offtopic"
} |
Why is javascript allowed in my post content?
The codex says you can't add javascript in the post content
<
But I can. I've turned off all plugins and changed to twentysixteen theme, but to no avail - I can still add javascript, via the post content, and have it run on the frontend. I don't want anyone to be able to add javascript through the post content (apart from oembed etc.) for security reasons.
Has anyone experienced this or have any ideas to help?
Thanks | If you have the unfiltered_html capability then you can use JS. Admins and editors have this capability by default.
Personally I use a plugin for fine control of my users' capabilities, but you can make this change easily in code:
$role = get_role( 'administrator' );
$role->remove_cap( 'unfiltered_html' );
$role = get_role( 'editor' );
$role->remove_cap( 'unfiltered_html' );
The capabilities are stored in the options db table, so technically you don't need to execute this repeatedly. Maybe make yourself a small plugin and put this on the activation hook.
Don't forget that admins could circumvent this by loading their own code and then directly editing the role options. I never let anyone have the admin role unless I'm happy for them to do anything. | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 9,
"tags": "filters, javascript, capabilities, post content"
} |
Different stylesheet for different pages not working fully
I am trying to use different stylesheets for different pages, but it doesnt kinda work. For example i made a page called 'Contact' and assigned the template contact-template.php to it.
and this is how i enqueued my stylesheets:
if(!is_admin()){
if(is_front_page()){
wp_enqueue_style('front-page-style', get_template_directory_uri() . '/style.css');
}
else if(is_page('contact-template.php')){
wp_enqueue_style('page-style', get_template_directory_uri() . '/style-contact.css');
}
else{
wp_enqueue_style('default-style', get_template_directory_uri() . '/style-default.css');
}
}
i already tryed using is_page_template('contact-template.php'); but not working... | Instead of:
is_page('contact-template.php')
Try:
is_page('contact')
`is_page` expects a post ID or slug.
If instead you want to enqueue this CSS for any page using this template, put the enqueueing PHP into the template itself. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, page template, wp enqueue style"
} |
Function to insert missing image size attributes into img tags
I want to add a custom function to scan my website and automatically insert image size attributes that are missing on my pages.
For example, if there is an image on one of my pages that looks like the following:
<img src=" alt="Image Title">
If `img.jpg` actual size is **150x50 px** , the function would pick up on that and insert the proper `width` and `height` tags:
<img width="150" height="50" src=" alt="Image Title"> | function replaceImageMeta( $imagename ) {
preg_match_all('/(alt|title|src)=("[^"]*")/i',$imagename, $img);//var_dump( str_replace("\"", "" , ( $img[2][0] ) ) );
list($width, $height, $type, $attr) = getimagesize( str_replace("\"", "" , ( $img[2][0] ) ));
$imgname = str_replace("\"", "" , ( $img[2][0] ) );
return sprintf('<img src="%s" width="%dpx" height="%dpx" >', str_replace("\"", "" , ( $img[2][0] ) ), $width, $height);
}
So call the function with image string
replaceImageMeta( "<img src=\" alt=\"Image Title\" >" ) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, images"
} |
How to create a link to jump to "Leave a comment" part?
I would like the create a link that point to the comment part. So when reader click on my link, it will scroll down to the place that they can leave a reply.
I have read some tutorial which teach how to create tag #id for headings in a post. However, I don't know how to do this for the comment part.
Please help! Thank you so much! | The code below should be something similar to what you're looking for
Inside the `loop template` you use for listing blogs (like `index.php`) you need something like this
<a href="<?php the_permalink(); ?>/#respond"> <!-- The blog permalink with the anchor ID after -->
<i class="fa fa-comments-o"></i> Leave a Comment
</a>
Inside your `comments.php` file you could have this
<?php if ('open' == $post->comment_status) : ?>
<div id="respond"> <!-- This is the element we are pointing to -->
<!-- Code for comments... -->
</div>
<?php endif; // if you delete this the sky will fall on your head ?> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "comments, links, id, buttons"
} |
Single.php the_excerpt loads same as the_content not loading read more line
Currently I'm using the the_excerpt on my frontpage which works perfectly. When the visiter goes to the post it first needs to read the first part of the story, see a featured image and then load the rest of the content.
Currently I have this:
<?php the_excerpt(); ?>
<?php the_post_thumbnail( 'blog-full', array( 'class' => 'img-responsive img-blog' ) ); ?>
<?php the_content(); ?>
The problem is, the_excerpt loads the same first lines as the_content (it's a duplicate). I inserted a read more tag in WP backend, but it won't cut of the top and start after the tag line.
How do I get this working?
Thanks in advance | You could do this without having to code anything special. Enter your first piece of text into the Excerpt field in the admin edit screen for the post. Enter only the remaining text into the visual editor.
That way you can have the excerpt text on the site's front page and the "rest" of the text after the thumbnail on the post's single page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development, the content, single, excerpt"
} |
Intercepting wp_mail() to view contents
I'm looking for a way to hook into the mail function before it sends so I can var_dump the output. **Are there any action hooks with the mail message that I can hook into?** I'm having trouble finding the `wp_mail()` function in core. Any other methods of debugging mail output would be greatly appreciated as well. | The first link on Google is to < which says that wp_mail is in wp-includes/pluggable.php
It also has the full function source code showing that the first active line of the function is:
`$atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) );`
... which suggests that if you hook into the filter you can capture all of those fields.
Additionally as it's a pluggable function you could also replace it with your own function doing whatever you want with the messages. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "debug, wp mail"
} |
Sanitizing textarea for wp_insert_post with TinyMCE enabled or disabled
I'm saving a post data from a front end form, where there is a `<textarea>`. I need to sanitize it properly so that won't be harmful by any kind. The textarea can be a plain text area or, if TinyMCE activated, it can become a rich text editor, but may be not with all sort of buttons, may be with basic text formatting features like bold, italic, anchor, quote, bullet points etc.
How can I sanitize the textarea data on saving the post from the front end, because there can be TinyMCE activated or deactivated.
Currently I'm doing no sanitization, because I thought `wp_insert_post()` will do that for me. But unfortunately it's taking wide range of HTML tags and that's messing my site.
What would be the best way to sanitize a textarea that can be either:
* A simple textarea, or
* A rich text editor with basic formatting buttons | All you need to know about the sanitization and escaping function is within the codex: <
In anycase, you should find usefull wp_kses_* functions, particular wp_kses_post
What function to use depend by what you want to filter and sanitize. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "tinymce, sanitization, esc textarea"
} |
How to add number to wordpress count function?
I am using a function on wordpress that accurately counts registered users. How could I edit this function code to add a number to the counter? For example, so it outputs registered users + 100.
This is the code I am currently using:
<?php
$result = count_users();
echo 'There are <b>', $result['total_users'], '</b> total
users.';
?>
Thank you | Er, `echo $result['total_users'] + 100;` ? | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions, users"
} |
How to export custom post type with ACF to individual file with automation?
I have a custom post type `product` using ACF (Advanced Custom Fields)
I would like to schedule a daily cron task automation to export all `published` posts into `post_id.txt`, one for each post.
I know there are plugins that can export custom post type and ACF to CSV or XML.
But my requirement is a more customized task.
A simplified example, the format of the output file `post_id.txt` should be and each field separated by `\n`:
eg. `1234.txt`
POST_TITLE
PRODUCT_IMAGE(ACF URL FIELD)
CATEGORY
TAGS
CONTENT
I can access all these information in the template loop, but how do I write a function to export them as the above job requirement?
Any pointer and direction of where to begin is appreciated. | Schedule your backup with WP Cron - <
In the cron event, run your query for posts or CPTs and be sure to add `'numberposts' => -1,` to return all.
When you loop through your posts from the resulting query, push the values to an array `$data[]=$some_string_data_for_prop;`
* <
* <
* <
And when you're ready to write the data, convert the array values to a single string; `$output = implode("\n", $data);`
Then write the data to a file `file_put_contents($filepath, $output);` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, customization, advanced custom fields, export, scheduled posts"
} |
Add post class to the TinyMCE iframe?
I want to add styles to `editor-style.css`, based on the category the current post belongs to.
Therefore I would like to add the post classes - using `get_post_class()` \- to the body of the TinyMCE iframe.
I've seen this question, but it's about adding classes via JavaScript, and I need it to be done via PHP so I can use `get_post_class()`. Neither can I use the `admin_body_class` filter, because that doesn't address the TinyMCE iframe.
How can I add the post's classes to the TinyMCE iframe? | The filter you're after is `tiny_mce_before_init`. Using this, we can hook into TinyMCE's 'init_array' and add body classes:
add_filter( 'tiny_mce_before_init', 'wpse_235194_tiny_mce_classes' );
function wpse_235194_tiny_mce_classes( $init_array ){
global $post;
if( is_a( $post, 'WP_Post' ) ){
$init_array['body_class'] .= ' ' . join( ' ', get_post_class( '', $post->ID ) );
}
return $init_array;
}
We're joining the post classes with a space to convert them from an array to a string as required by TinyMCE, and we're also checking that we do actually have a valid post object, to avoid errors if you're using TinyMCE elsewhere (such as in widgets or the like). | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 4,
"tags": "php, tinymce, iframe, body class"
} |
Genesis themes: how do alter the markup of post meta on archive pages?
I'm creating a site based on studiopress's executive pro theme. I'd like to remove the comment count that shows in the post meta in archive pages.
In a conventional WordPress workflow I would child the theme and edit the php directly.
In this particular case, I can't find the markup.
Is the post meta generated from a php template or a function? Where is it, and how can I alter it? | Within your Executive Pro theme's `functions.php`, you can add a function that filters the post info.
In Genesis `lib/functions/post.php`, you'll find a `genesis_post_info()` function, and one particular line in it is:
$filtered = apply_filters( 'genesis_post_info', '[post_date] ' . __( 'by', 'genesis' ) . ' [post_author_posts_link] [post_comments] [post_edit]' );
That means you can filter `genesis_post_info`, and not include the `[post_comments]` (and `[post_edit]` as that is available from the admin toolbar anyway) part of it.
add_filter( 'genesis_post_info', 'gmj_remove_comments_count' );
/**
* Remove comments count and Edit link from post info.
*
* @link
*/
function gmj_remove_comments_count() {
return '[post_date] ' . __( 'by', 'your-theme' ) . ' [post_author_posts_link]' );
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "genesis theme framework"
} |
Distributing Frontend Assets with Plugins
I'd like to distribute some custom style sheets (`.css`) and javascript files (`.js`) with my plugin. Is there a _right_ way to do this in Wordpress? I can think of a number of different ways to do this, but I'd prefer to use one that's Wordpress recommended, or a defacto time and true standard. Specifically
1. Where should I place my CSS/JS files? In `wp-content/plugins/my-plugin/css/etc.css`? Somewhere else?
2. How should I generate URLs to these assets in my plugin? `<?php site_url() . '/wp-content/plugins/my-plugin/css/etc.css ?>` Is it safe to hardcode `wp-content/plugin`, or is there a better function/functions to use? | 1 - it's up to you and subject to opinion, so not best suited to WPSE.
2 - Never hardcode paths. WP has whole range of functions for finding file paths and URLS. `plugins_url()` will get you the full URL to the plugins directory, handling whether you are using http or https and canonicalising the domain name for you. It will take parameters for a file relative to your plugin's directory by using PHP's magic `__FILE__` constant too: `plugins_url( 'images/plugin_icon.png', __FILE__ )` for example.
Similarly, `plugin_dir_path( __FILE__ )` within a plugin file will get the full system file path to the file. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, css, admin css"
} |
How to delete user roles?
I installed BuddyPress which created additional user roles but even after deleting BuddyPress those roles are still there. How can I delete these roles? I have tried the `remove_role()` command but it did not work. | $wp_roles = new WP_Roles(); // create new role object
$wp_roles->remove_role('name_of_role');
If you need to check the **name_of_role** use
$wp_roles->get_names();
you will get an array of **name_of_role** => **Nicename of Role**
Alternatively, you could use the global object **$wp_roles**
global $wp_roles; | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "user roles, buddypress, customization"
} |
How to not load comments form on post preview?
I need a way not to load the comments form when previewing a post, is there a way to achieve this? How?
If you need a reason to help: I use disqus and it generates a url for the "discussion" the first time the comment form loads, if this is the preview then it will look something like site.com/?post_type=food&p=41009 And this is a problem because afterwards when the post is published under a real url disqus will not recognize the comments count. The only way is to manually change the discussion url. I've already contacted disqus and they say, "not a bug" if you do not want disqus to pick the preview url, don't load disqus on the preview page, the only way i know is to completely remove the comments form, so how would i go about this? Is there some sort of conditional for the preview page? | I took a quick peek at the disqus plugin. This works in disabling the option before the plugin decides to print out the form.
add_filter( 'pre_option_disqus_active', 'wpse_conditional_disqus_load' );
function wpse_conditional_disqus_load( $disqus_active ) {
if( is_preview() ){
return '0';
}
return $disqus_active;
}
You could also try something like this (not tested)
add_filter( 'the_content', 'wpse_load_disqus');
function wpse_load_disqus( $content ){
if( is_preview() ){
return $content;
}
if( is_singular() ) { // displays on all single post types. use is_single for posts only, is_page for pages only
$content .= ?>
// You disqus script here
<?php ;
}
return $content;
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "comments, disqus"
} |
What plugin development paradigm differences have occurred between version 3.5 and now?
I have books that are not at the current version of WordPress, but they might still be of some value. If I learned to develop on 3.5 or 4.0, for example, but later on 4.x+, would it be completely different to work on the newest version? | This is a pretty broad question, but I will still try to answer it.
WordPress is a mature platform so you won't see many changes between 3.5 and the current version that would require you to learn from scratch. The basics of WordPress are still the same with some additional features that will make your life easier added since 3.5. You might stumble upon a function call or action/filter hook that has been deprecated, but there aren't many of them and, as long as you develop with `WP_DEBUG` enabled you will be fine.
WordPress books or online courses are a good starting point to get a grasp of basics (how the loop works, templating hierarchy etc.) and these haven't changed. Beyond that, WordPress Codex is your best friend and, regardless of WordPress version, you will spend most of your time there. Just remember to always use/develop the most recent version of WordPress. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development"
} |
How do I correctly query posts from a post ID?
Ok so I have this code to Query posts from a certain ID:
<?php
$valid_post_types = array ('agencies','pro-awards-winners','marcawards','topshops');
$args = array(
'post_type' => $valid_post_types,
'post_status' => 'publish',
'pagename' => 210639,
'posts_per_page' => -1
);
$query = new WP_Query( $args );
// The Query
query_posts( $args );
//The Loop
while ( have_posts() ) : the_post();
echo '
<li>';
the_title();
echo '</li>';
endwhile;
// Reset Query
wp_reset_query();
?>
The posts aren't displaying of course...Is there something I'm doing wrong? | I solved the problem by posting adding this: `$list_args2 = array( "post_type" => "any", "post__in" => get_post_meta( 210639, 'storylist', true), "orderby" => "post__in", 'post_status' => 'publish' );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "custom post types, wp query, loop, query posts, get posts"
} |
What is the valid phone number format accepted by contact-form-7
What is correct phone number format supported by contact form 7 telephone field. Is it something like `###-###-##` or `### ### ##` or `########` or `+# #######` or any other ?
I tried searching about the format, but couldn't get any result. I'm trying to implement a client side validation check, for which I need to know format that is applied on server side by contact form 7. | A quick look for `tel` in the plugin gives me this check for telephone numbers:
function wpcf7_is_tel( $tel ) {
$result = preg_match( '%^[+]?[0-9()/ -]*$%', $tel );
return apply_filters( 'wpcf7_is_tel', $result, $tel );
}
Using the above function the plugin is validating whether the user input is a valid `tel` or not. So the above regex is the one that is used for validation. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "forms, plugin contact form 7"
} |
WordPress get_template_part() function not working
I'm using `get_template_part()` function on my file (`page-home.php`) like page-home.php and it is working fine until I called it 5 times on the same file (`page-home.php`) but when I called it 6th times like
<?php get_template_part( 'template-parts/content', 'project' ); ?>
data from advanced custom field plugin is not showing, but the data from `Custom Post Type UI` plugin is showing correctly and if I delete any of the above `get_template_part()` the data from `<?php get_template_part( 'template-parts/content', 'project' ); ?>`is showing correctly.
Any type of help is appreciated. | Looks like your problem is in the `content-project.php` file. Whenever using `WP_Query()` make sure to use `wp_reset_postdata();` Additional details can be found here | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "theme development, themes, advanced custom fields"
} |
Custom Taxonomy Archive Page
I have created a Custom Post Type with the name Product. I have created a Custom Taxonomy for that post type by the name of products. That taxonomy have a few terms (printer, keyboard, mouse etc) I have created a template with the name taxonomy-products.php
If I visit the url **example.com/products/printer/** it loads the taxonomy template and correctly displays the posts that are attached to that term.
My problem: if I visit the url **example.com/products/** I get a 404 error.
My question: is there a template file for the taxonomy archive page? | That is how taxonomies works by default in WordPress. There is not an archive page for "All posts that belongs to any term of a taxonomy". And, conceptually, it is correct.
Imagine you want to list all _items_ of a biological taxonomy system: that is listing all organisms. If you translate to posts, it is what blog and custom post types archives do.
Same applies for core taxonomies, categories and tags, if you go to `example.com/category/` or `example.com/tag/`, you will get a "404 Not found" HTTP code status, which is correct.
If you want to have the URL `example.com/products` display some content, you can create a page, or a Rewrite Endpoint, and make a custom query for that URL. | stackexchange-wordpress | {
"answer_score": 6,
"question_score": 7,
"tags": "custom taxonomy, templates"
} |
Searching Posts Programmatically in a Wordpress Plugin
If I navigate to `Posts -> All Posts` in a Wordpress install, there's a Search Box in the upper right hand corner. Entering terms in this box and clicking the Search Posts button will perform a search.
Does Wordpress provide a hook, function, or other API that would allow me to programmatically perform the same (or a similar) search? i.e. I pass in a string as terms and get back a PHP array of results without needing to write any SQL myself.
If not, does anyone here know where in the Wordpress core code the above search happens? (so I cam mimic the behavior as best as possible)
Thank you! | > Per comments above from mmm
Try this
$posts = get_posts(["s" => "string to search"]);
Also, Covering the `get_posts` API is a bit beyond a single StackExchange answer, but if you want to dive deep you'll find more informations in the codex. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, search, sql"
} |
Displaying pages with a specific custom meta
Basically I have 3 Custom Meta checkboxes that I want to be able to filter by let's just use Member 1, Member 2, and Member 3 for these.
The kicker however is that some may use 2,or even all 3 of these.
What I need to be able to do is list all of the pages that have one checked. So a page called 'Member 1' would display anyone with that tag. 'Member 2' would display the same and so on. I've been told that I may be able to accomplish this with `wp_list_pages()`, but I've had no luck so far.
Also is there a way that I can make my menu dropdowns automatically display these. Like I have a menu labelled Member 1 and when I hover over it, it will show all of the Member 1 checked pages?
Any thoughts? | You'll need to test that this works, but I've just been looking at source and I think it will.
`wp_list_pages` doesn't officially take meta keys or values in its arguments, but it _does_ pass its argument array straight on to `get_pages`, which does allow you to make a meta query. So, you _ought_ to be able to do this to get pages where the custom field `member_2` has the value `yes`:
echo wp_list_pages( array(
'meta_key' => 'member_2',
'meta_value' => 'yes',
) );
I'd be interested to know if it works! | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field, metabox, wp list pages"
} |
Ways to work offline with your WordPress
I want to work on my WordPress using my shared hosting space and then do a backup and upload it in my client hosting space, is that possible? I am novice and I am struggling in how get working on the website before launching it, I read about MAMP but not sure if it will do the trick, I just want to be able to work on the website and once is ready I can upload it without hassle. Can anyone help me with some tips? | MAMP is the quickest route to a local dev environment.
You can also use your Mac as a LAMP server without to much trouble, I found this more stable and easier to recreate server conditions than using MAMP. This is an excellent guide <
A 3rd option is to start using Docker... This is my current choice as (if you use Docker on your prod server) you can recreate conditions exactly and each site can have its own config within a container
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "migration"
} |
tinymce custom button
I'm building Storefront child theme. I'm trying to add woocommerce shortcodes plugin into the my theme.
Button added but can't load translation file.
 {
$locales['woocommerce_shortcodes'] = get_stylesheet_directory_uri() . '/inc/woocommerce-shortcodes/wc-shortcodes-editor-i18n.php';
return $locales;
} | Changed `get_stylesheet_directory_uri()` to `get_stylesheet_directory()`, and it works. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, woocommerce offtopic, tinymce"
} |
Load images with http urls inside https post
I have a archive page which is running under `https`. It doesn't loading any images within the post as all the image urls with `http`.
It is giving an error like bellow,
Blocked loading mixed active content "
How should I avoid that errors and load the images on that page.
I saw in a article simplest way to fix it by converting urls into relative urls.
eg:
-> //wp-content/uploads/image.jpg
Any idea how should I do that ? | simply used the `str_replace` function to convert the urls to `https`
$content = get_the_content();
$content = apply_filters( 'the_content', $content );
$content = str_replace( ']]>', ']]>', $content );
$content = str_replace(" " $content);
echo $content;
event you can make the relative urls with this way. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 4,
"tags": "urls, https"
} |
Recent Posts Widget URL / Domain change
we use the "Recent Posts Widget" within our page footer. After we changed the site URL from development to live the links of the "Recent Posts Widget" didn't change.
First we used the plugin "Search & Replace" to change the domain within the database. Second we changed left over domains by hand within the backend. But we coulnd't find a where to change the links within the "Recent Posts Widget". We deleted the widget from the footer and recreated it but that didn't change anything.
Any idea what went wrong or how we can change the domain?
Thanks for your time.
Best regards Klaas | I was able to resolve the problem. After looking throu the theme/plugin code i noticed that it was altered before and the false links were hardcoded into it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "widgets, footer, recent posts"
} |
How to add if lt IE9 conditional scripts to functions.php
I am trying to enqueue a conditional javascript file for lt IE9 in the functions.php file (in Wordpress). For anyone viewing the website in IE9 this script will be triggered. Is what I have below anywhere near correct? That jQuery $ will cause problems because of Wordpress runs in nonConflict mode. But this was the only answer I have found. I already have multiple style sheets and scripts running in my functions.php file with no bother.
global $wp_scripts;
wp_register_script( 'ie_js', '/js/ie.js, array(), '' );
$wp_scripts->add_data( 'ie_js', 'conditional', 'lt IE 9' ); | Yes, that looks broadly correct (barring a missing `'`). That isn't a jQuery `$`, so shouldn't cause any problems - the dollar prefix here is the usual convention for PHP variable names and won't make it into the included script.
Or if I've misunderstood and you meant your ie.js script assumes jQuery is `$` then you can solve that by wrapping it in a self-executing function which defines a scope where $ = jQuery, e.g.
(function($){
...
})(jQuery);
Also as of 4.2 there's a helper function wp_script_add_data so you can write instead:
wp_register_script( 'ie_js', '/js/ie.js', array(), '' );
wp_script_add_data( 'ie_js', 'conditional', 'lt IE 9' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "javascript"
} |
complex query question
scenerio: I have several events in a CPT called events. For single events, they use template single-event.php. I also have guest speakers, in which each one has post in a CPT called speakers.
I'd like to create a query that pulls a custom field from a speaker post with a key's value that matches the event title.
The idea is to display a subset of my speakers on a specific event based on the meta value of the speaker post using a single event template page. | It's pretty easy actually in your `single-event.php` file within the content loop. add this loop where you want your speakers information to show.
$event_title = get_the_title(); // This is the title of the current single event page we are on.
$args = array(
'meta_key' => 'event_name', // the name of your custom field
'meta_value' => $event_title,
'post_type' => 'speakers',
);
$speakers_query = new WP_Query( $args );
if( $speakers_query->have_posts() ) :
echo '<ul>'; // start your section here
while( $speakers_query->have_posts() ) : $speakers_query->the_post();
// echo your speaker content here like name, images, etc.
echo '<li>' . get_the_title() . '</li>';
endwhile;
echo '</ul>'; // end your section here
wp_reset_postdata();
endif; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, wpdb"
} |
How to add 2 variable rewrite rule?
I want to end up with url structure for galleries like the one below ;
<
as you see there will be two variables.
I separated templates like content-default and content-gallery.. So far it's OK. But what should i do to open a single gallery element page when user goes to this link? | OK. Here is my final solution.. Wordpress already has this opportunity for attached galleries.. Check if your theme already has a file called `attachment.php` otherwise create one and copy the content of `single.php` and modify.
This solution does the trick for me. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, gallery, slug"
} |
Unsure of my options, Multi-blog?
I'm looking to create a system where people can sign up and post content to my blog. A bit like each user having their own mini blog within my main one. The blog site is based on car projects that all fall under one general niche, having subaru engine swaps.
What I'd like to achieve is a system where a user creates a project folder/category before they are able to post content, for example if I wanted to post about my own project I would have to create a category for that like 1972 VWRX Bug.
Then each time I wanted to update something about that build/project it would be assigned to that project, allowing any visitor to the website the ability to view the project from start to finish.
By doing it this way I would hope that I could also create just a gallery that pulls all photos from the project, or a blog page showing all the posts/images and content.
What options do I have here, is there a way to achieve this? | After a lot of searching around, it occurred to me that what I was trying to do was essentially to create a social network. Having search for Wordpress Social Network plugins I discovered and am using Buddypress. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "multisite, users"
} |
What actions affect files, DB, or both?
I'm looking into setting up a development -> staging -> production workflow, and the biggest issue so far is figuring out how to sync the databases.
To this end, I'm trying to figure out exactly which actions will affect the filesystem, the database, or both. Here's how I think it works. Please correct me where I'm wrong, and let me know if my questionable answers are right!
* Registering a new user - database
* Adding a post or comment - database
* Changing to a new theme - database?
* Changing a theme's settings - database
* Installing or removing a plugin - filesystem
* Activating, or deactivating a plugin - filesystem
* Updating a plugin - filesystem and database? (DB structure may change?)
* Changing a plugin's settings - database
* Uploading media - filesystem and database?
* Editing custom files not included in a theme or plugin - filesystem
* Upgrading Wordpress - filesystem? | * Registering a new user - database
* Adding a post or comment - database
* Changing to a new theme - database(yes)
* Changing a theme's settings - database
* Installing or removing a plugin - file system,database
* Activating, or deactivating a plugin - file system,database
* Updating a plugin - file system and database (DB structure may change if plugin has custom tables registered and in the new version if it has structure changes)
* Changing a plugin's settings - database
* Uploading media - file system and database
* Editing custom files not included in a theme or plugin - file system(this depends on the actions you are taking)
* Upgrading WordPress - file system,database | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "database, customization, staging, workflow, production"
} |
How to modify wp_config file for set up subdirectory?
am not a programmer. currently creating a multisite on wordpress. I want to create a subdirectory. here's the code for subdomain. how can i change it for subdirectory.
/* Multisite */
define( 'WP_ALLOW_MULTISITE', true );
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', true);
define('DOMAIN_CURRENT_SITE', 'www.mysite.com');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1); | Just change `define( 'SUBDOMAIN_INSTALL', true );` to `define( 'SUBDOMAIN_INSTALL', false );`
More here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "multisite, wp config"
} |
WordPress automatic publish: is there a timeout when WordPress won't publish anymore?
When you schedule a post for publish, and it misses its publish time, for how long after that will WordPress publish it?
I know that WordPress cron jobs trigger when a user loads the page after the cron job is set to run, but how long after the scheduling time will WordPress still publish the post?
E.g: If the publish time is set to 12:00 pm, and the first user after 12:00 visits 12:30 pm, will WordPress still publish? What is the limit here?
I will admit that I didn't google that much before asking, but I saw mostly tutorials on how to set up the publishing. | There is no limit. Once the next person visits the site the cron queue runs regardless of how much of a gap there has been.
The only caveat is that if you have a job that you've scheduled to run hourly and 2hrs pass between vists to the site, the job will only run once when the next person comes. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "wp cron, cron, scheduled posts"
} |
Plugin installation works only with FTP - how to debug?
When I install new plugins in the Admin, Wordpress **asks for FTP access** although the **file permissions should be correct**. I want to enable plugin installation without ftp access.
**How should I debug this problem?**
One special thing about my installation:
* I do not use the usual location for the wp-content folder and instead
> define('WP_CONTENT_DIR', realpath(ABSPATH . '../wp-content/')); define('WP_CONTENT_URL', WP_HOME . '/wp-content');
What I've tried up to now:
* Find out who the apache user is:
> $ ps aux |grep apache
> www-data 9040 0.0 1.8 280912 9160 ? S 10:49 0:00 /usr/sbin /apache2 -k start
* Adjust the permissions and ownership of the plugins folder such that
> $ ls -ld wp-content/plugins
> drwxr-xr-x 12 www-data myself 4096 Aug 10 20:31 wp-content/plugins
How should I search for the reason why this does not help? | I've found the answer here.
In brief, Wordpress performed some checks to see if it has enough write permissions, and those checks failed.
To skip those tests and simply create the files, one must place this somewhere in the `wp-config.php` file:
> define('FS_METHOD', 'direct'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "plugins, installation, filesystem"
} |
Dynamic Home Page based on Log in status
I want to build the home page to show just a login box when logged out and the normal home page when logged in.
Alternatively i can also allow redirection to another page when a logged in user clicks home.
I am using WP membership plugin for membership access.
Thanks | You can put this on your in your home page template or in your header.php (if you want to use across your entire site).
<?php
if ( !is_user_logged_in() ) {
auth_redirect();
}
?>
Details in the Wordpress codex... < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "membership, members, s2member, plugin members"
} |
Remove dash from blog title wordpress
Hi this is my first time using wordpress and php, I created a static page for my front page of the site, and got my news on a separate section, I'm just wondering how do i remove the the dash from the wordpress title in the blog. I understand that its trying pull through the page number, but now that's not required I just need to remove the dash fromwp_title. Sorry if this post is a duplicate, as I couldn't find any information regarding this topic. | This is not quite trivial in general case, since it varies depending on title implementation by _specific theme_.
The historical way has been `wp_title()` call in theme's template. The newer method is hook–based Title Tag.
So it is hard to say specifically without knowing/seeing code of a specific theme.
This is one of the reasons for high popularity of SEO plugins, for many of which manipulating titles in more user–centric ways is one of the main features. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, wp title"
} |
Is it possible to reverse the order of a list of posts pulled from a loop?
I want to pull the three most recent posts from a specific category. I have the code to do that, but I'm trying to figure out if there's a way to reverse the order of these three posts when displaying/pulling the data?
Current Code:
'category_name' => 'dvd-report',
'posts_per_page' => 3,
) );
if ($cinemasight_header_query->have_posts()) :
while($cinemasight_header_query->have_posts()) :
$cinemasight_header_query->the_post();?>
<span class="Categories_Lower_Right">
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a><br />
</span>
<?php endwhile;
endif;
wp_reset_postdata();?> | Assuming you are refering to the code of this answer
Taking the query from that answer
$args = array(
'category_name' => 'your-category-slug',
'posts_per_page' => 3,
);
$wpse_235685_query = new WP_Query( $args );
you would then, to reverse the order of your results, need to modify the query `$posts` object, like so
$temp_posts = $wpse_235685_query->posts; // store the posts to work with
$wpse_235685_query->posts = array(); // empty the $posts object
$wpse_235685_query->posts = array_reverse($temp_post); // set back the object to use new reverse order
of course this could be simplified by getting rid of the temporary variable like so
$wpse_235685_query->posts = array_reverse( $wpse_235685_query->posts );
This code should go between your `if( $wpse_235685_query->have_posts() ) :` and your `while( $wpse_235685_query->have_posts() ) :` so it doesn't run when the query returns an empty set. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "loop"
} |
Vendor Listing by Location
I am trying to implement a solution provided at wcvendors.com knowledgebase and unable to get the indicated results. Can somebody help me with the implementation as to where this is going wrong. I am a beginner at wordpress and php.
Basically, I am trying to list vendors by their store location. For this i am using wc vendors multi vendor marketplace plugin. I have created a dropdown custom field as indicated in the code. The custom fields are coming up at the registration time and also reflected in the user profile for view and edit. I want to filter the vendors on this meta key to have vendors categorised by their location.
IF there is any other option to do that it would be a great thing. | Another way I figured out is using custom taxonomies and product filter plugins.
Very simple and easy to implement in any part of the web page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
How to display custom taxonomy images on index.php?
i want to display custom taxonomy images on index.php and for this reason i installed this plugin. I uploaded my taxonomy images but i couldn't display images on index. I tried the codes which are given by the plugin author.
<?php
print apply_filters( 'taxonomy-images-queried-term-image', '' );
?>
etc. But it didn't work. I think this code has no echo function, am i right? And the URL, which you can see the below, is my custom taxonomy URL.
edit-tags.php?taxonomy=ff-portfolio-tag&post_type=portfolio
So how can i display my custom taxonomy images on index.php? Thanks a lot. | Just like we use `get_terms()` to get all the terms in a custom taxonomy we can get all the taxonomy images with the below code. Place this code outside the loop to list all the taxonomy images.
$terms = apply_filters( 'taxonomy-images-get-terms', '', array(
'taxonomy' => 'ff-portfolio-tag',
) );
if ( ! empty( $terms ) ) {
print '<ul>';
foreach ( (array) $terms as $term ) {
print '<li><a href="' . esc_url( get_term_link( $term, $term->taxonomy ) ) . '">' . wp_get_attachment_image( $term->image_id, 'detail' ) . '</li>';
}
print '</ul>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom taxonomy, images, taxonomy"
} |
Show Sidebar Menu Subpages When Clicking Parent
I have a sidebar nav menu set up to display the top level pages. I'd like to display subpages (3rd level) when a user clicks on a parent item. For example, when then user clicks 'Detective Division' the two subpages (Violent Crimes and Property Crimes) will show.
); ?>
</div>
Is this controlled with 'depth' or do I need to use a walker? | No need for a custom walker - it's controlled with the `depth` parameter. At the moment, you're only showing 2 levels of menus - but you need to set this to `3`!
This, however, will only control what is being output. As for the user clicking, hovering or otherwise to actually see the menu, you'll need to apply your own formatting (usually just CSS, although you could use JavaScript too) on the frontend in order to affect the display. WordPress doesn't handle this for you by default as its up to the theme. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus, walker"
} |
Add infinite scroll to content splitted post
I'm using `<!--nextpage-->` tag to split up the post content into multiple pages. My example post content looks like this:
<img src="1.jpg" alt=""/><!--nextpage-->
<img src="2.jpg" alt=""/><!--nextpage-->
<img src="3.jpg" alt=""/><!--nextpage-->
<img src="4.jpg" alt=""/>
I want to setup infinite scrolling so when a user scrolls down the page it'll load the next image/content of the post. Is there a way to do this? There are lots of tutorials on adding infinite scrolling to posts but they only load more posts where as I want to load more of the post content | Your best bet is to use a combination of JS waypoint libraries with the WP Rest API.
When element is visible, fetch content and display. Pretty simple.
Instead of the `<nextpage>` you could also wrap this in a custom shortcode but this is primarily a JS problem, not really a WP issue. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -7,
"tags": "pages, javascript, navigation, content"
} |
Unset a Cookie on Successful Gravity Forms form Submission
I have a cookie with data that I'm utilizing to populate a Gravity Forms form. However, after the form has been successfully submitted, I'd like to unset (or more accurately, expire) that cookie.
### What I've tried
Initially, I thought the `gform_after_submission` hook would work. I tried simply that pointing to a function that does the following:
public static function clearItems() {
setcookie('items', '', time() - 86400, '/');
}
The problem is that this hook is executed after the headers and therefore the updated value and expiration are not set.
### Question
Is there any way to accomplish this (maybe I'm missing a hook of some kind that would work better)?
Another possibility that I've considered is to redirect to page and handle it there but I'd prefer not do handle it this way. | I ran this code to try setting a cookie on the `gform_after_submission` hook and it worked as expected.
add_action( 'gform_after_submission', function() {
setcookie( 'boom', 'boom', time() + 3600, '/' );
} );
The headers should not already be sent when the `gform_after_submission` action is triggered. If you're getting a warning about this, there might be something else outputting something to the page earlier in the process. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "cookies, plugin gravity forms"
} |
Help with Wordpress RSS Validation Error
I was trying to link my site (< to Bloglovin. However it wasn't showing my post, so I emailed support and I was told there was an issue with RSS validation for my site.
I have looked everywhere and tried out plugins and stuff and nothing seems to work.
Can anyone please help out?
Here is the link to the Validation checker to see for yourself: < | If you look at the validator output, you will see there is a little red arrow pointing to the space between "knows" and "me". Copy "knows me" to a simple text editor like Notepad and you will see that the blank space consists of two characters, a space and an unknown invisible one.
To get rid of the last one, delete "knows me" and retype it, making sure you are not hitting any weird keys on your keyboard. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "rss, validation"
} |
Output wp_link_pages as raw url
My post content looks like this
<img src=" alt=""/>
<!--nextpage-->
<img src=" alt=""/>
<!--nextpage-->
<img src=" alt=""/>
<!--nextpage-->
Basically I'm trying to make a web comic book so I have made each image to split onto multiple pages using the `<!--nextpage-->` feature. Now the problem is I want my images to be linked to the next paginated post. I can't use `<?php wp_link_pages(); ?>` to make a hyperlink on the image cause wp_link_pages outputs it as html and I need it as raw url and I don't need prev & next link. I only need a next link on the image.
Is this a way to make my images to be hyperlinked to the next paginated post? | If you take a look at the link generated by the `<!--nextpage-->` tag, it just appends `/2` for page 2 `/3` for page 3 and so on. In other words, it adds a query string `page=page_number` to your post link.
So all you have to do is insert an hyperlink to your image with the next page number for that image.
you still need to add the `<!--nextpage-->` tag because that will break your post in multiple pages. If you don't all your images will all appear on each paginated page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, images, pagination, navigation, paginate links"
} |
Is there a way to remove wp-login.php alias (login)?
I recently was looking at my web server logs, and I saw something like this:
"GET /login HTTP/1.1" 301 448 "-" "Python-urllib/2.7"
"GET /login HTTP/1.1" 302 4563 "-" "Python-urllib/2.7"
"GET /wp-login.php HTTP/1.1" 403 3982 "-" "Python-urllib/2.7"
My wordpress installation is a little bit different, and I use certificates to protect the `wp-login.php` file and `wp-admin` directory. So without the certificate, you will be redirected to the main page, unless you are a bot like in this case.
The solution works fine, but I want to eliminate the extra queries you see above. So the question is how to remove the `login` alias, so the login page would appear only when you type `wp-login.php`. | This is the result of a default action, so you can remove it in a plugin with:
remove_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );
You could also just block `Python-urllib` in your server configuration. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "login"
} |
Is there a way to add more tags to the tag cloud?
I have over 100 tags on my blog, but in the tag cloud there's less that 50. I don't really care about that, but I want to align the widgets in the blog footer, so I need to add 10 or 20 more tags to the cloud. Is there a way to do it? | The tag cloud widget uses `wp_tag_cloud()` to display the tags, which defaults to 45 tags.
Source: <
One can use the `widget_tag_cloud_args` filter to change this number (and any other arguments passed to `wp_tag_cloud()`. Here's an example:
function wpse_235908_tag_cloud_args( $args ) {
$args['number'] = 70; // the number of tags you want to display.
return $args;
}
add_filter( 'widget_tag_cloud_args', 'wpse_235908_tag_cloud_args' );
You can add this piece of code in a custom plugin or your theme's function.php file for example.
Note: There's also a doc reference for the `widget_tag_cloud_args` filter, but the documentation is currently wrong as per this core ticket. | stackexchange-wordpress | {
"answer_score": 8,
"question_score": 4,
"tags": "widgets, tags"
} |
how to use a default MO file
I've created a plugin that uses `gettext` to localize the strings. Here is a sample line of code from my plugin:
__("not less than ",'mytextdomain')
I realize that `not less than` is actually the identifier, not the real string, but gettext outputs that if it doesn't find the MO file for the current locale.
Now I'd like to use _real_ identifiers, and have gettext output the string from a default MO file if it doesn't find the one for the current locale.
How do I set one of the MO files to be the default one? Seems strange to me, but I've googled for "gettext default locale" and similar things without luck. | Be careful: `not less than` is **not** the identfier, but indeed the real English string that should be used by default. In WordPress, you'd use it like this:
`__( 'Hello World', 'mytextdomain' );`
If someones translates it into `de_DE`, they would translate `Hello World` to `Hallo Welt`.
To answer your question: the default locale in WordPress is en_US. So you could theoretically add a `en_US.mo` file that "translates" your default text. However, since en_US is the default, it's not needed nor recommended.
Let me know if you need more help with i18n inside WordPress and I'll happily extend my answer. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "localization"
} |
javascript not being enqueued correctly
I have the following in my child theme's `functions.php`:
add_action( 'ors_enqueue_scripts', 'enqueue_parent_theme_style' );
function enqueue_parent_theme_style() {
wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri().'/style.css' );
wp_enqueue_script('ors-animations', get_stylesheet_directory_uri().'/javascripts/animations.js', array( 'jquery' ));
}
The child theme is active, however, the file `www.example.com/wp-content/themes/child-theme/javascripts/animations.js` is not being enqueued.
Help appreciated. | I think you have typo in your code: ors_enqueue_scripts should be wp_enqueue_scripts
add_action( 'wp_enqueue_scripts', 'enqueue_parent_theme_style' );
function enqueue_parent_theme_style()
{
wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri().'/style.css' );
wp_enqueue_script('ors-animations', get_stylesheet_directory_uri().'/javascripts/animations.js', array( 'jquery' ));
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "child theme, wp enqueue script"
} |
Loading css files conditionally useful?
I've read some articles, which states that it would be useful to load javascript files conditionally, based on the fact if they are needed on a site or not. Therefore I start to exclude custom js from those pages, which do not use those elements.
Now I want to know if the same applies to the custom.css - I know that I should include one custom.css file, which will be gzipped and maybe cached on a second domain/cnd. But what, if I use a custom sub navigation only on few sites and the css rules for this nav are taking 40kb for example? Would it be best practice to create another css file for this scenario and only load it on the relevant sites? | There is no hard rule on this.
Loading JS is discussed often because JS is more likely to _conflict_ when a lot of plugins throw their scripts into the mix.
CSS is less problematic in that regard. Still the same premise apply — you should aim for solution that _performs well_.
In a situation you describe, with highly contextual sites of large size, it certainly makes sense to separate them into dedicated stylesheet.
In other cases complicating development and logic for insignificant benefit might be impractical. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, performance"
} |
wp_insert_post: array only. wp_update_post: array|object (?)
I just noticed PHPStorm "complaining" that my first argument to wp_insert_post is an object, where an array is expected.
I also noticed that there's no such complaint with wp_upate_post.
It would be somewhat of a pain to refactor my code to use an array for every call to `wp_insert_post`, and furthermore the mismatch doesn't seem to cause any issues -- I suppose it is being automatically cast by PHP (?)
Is this something I ought to address or is it safe to leave as-is? I guess this might be more of a PHP concern than WP.
It did seem odd to me that two closely related functions like this have different argument type specifications. | Array's are technically preferred for both, but it actually doesn't matter that much. PHP is not casting the object to an array, worpress is. `wp_insert_post()`, like a lot of wordpress functions, runs it's "array" parameter through `wp_parse_args()` which will cast an object passed to it to an array and will always returns an array.
You _should_ probably address it in case wordpress ever released an update where they stopped casting the object for you and PHP will throw a fatal error if you try to use an object as an array. But frankly, that casting probably isn't super likely to be removed any time soon.
If you did want to fix it, all you would have to do is replace
wp_insert_post($object);
with
wp_insert_post(get_object_vars($object)); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, plugin development"
} |
403 Forbidden on site logo image upload
When uploading a site logo, I get a 403 Forbidden HTTP error.
Also, the Inspect Element preview shows this page:

This is a default install from Wordpress stable version. I have removed my plugins folder too, no change. My web server is NGINX. | So after a good bit of debugging around, I discovered it was that posting over 64 KB(16-bit integer length) of data would cause my modified NGINX to not split up post data in FCGI. After fixing that, it working great. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "errors, nonce"
} |
why my WordPress theme doesn't support shortcode?
I just create a simple WordPress theme, everything looks fine but when I use a plugins which need shortcode.
I put the short code in a page (like this [user-submitted-posts]), on front end, it show same short code. When I change to another theme, the short code works fine.
Shortcode doesn't work, is this need function.php support it? | You should add to theme something like this:
add_filter('shortcode_function_name', 'do_shortcode');
This should be enough. Here you can find the documentation related to the shortcodes:
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -3,
"tags": "theme development, shortcode"
} |
I am getting useless alphabets in images link
I dont know why i am getting extra alphabets and question mark in my image links. Please take a look
 URLs.
But in this case, media files will remain cached by the visitor's browser until the browser cache will be emptied or query string will be attached again in URL.
P.S. Maybe you'll need to update media query string by pressing the button on the same settings page. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "images, links, cache, plugin w3 total cache"
} |
Different slug taxonomy for two different CPT
I want to use a one taxonomy of two CPT. But I want to have different URL.
Like this:
**city** \- taxonomy (taxonomy data is used in two CPT)
**people** \- CPT
**car** \- CPT
I want:
site.com/people/born/LA
site.com/car/place/LA
Thus in the first case I show people born in the LA, and in the second case, cars being in LA | You can share a taxonomy between multiple custom post types.
You will need to register the taxonomy in your plugin file or theme's functions.php file:
`<?php register_taxonomy( $taxonomy, $object_type, $args ); ?>`
WP Codex: Registering Taxonomies
When you register your taxonomy you will need to use an array for the $object_type. In this example the taxonomy "city" is being assigned to the "people" and "cars" post types:
register_taxonomy(
'city',
array( 'people','cars' ),
array( 'hierarchical' => true,
'label' => __('City'),
'query_var' => 'city',
'rewrite' => array( 'slug' => 'city' )
) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, custom taxonomy, slug"
} |
How to remove header "ish" label
I've been trying to remove this for an extented period of time, and it seems to be easy to remove.
 . '</span></li>';
i changed it to this:
the_modified_date('j F Y', '<li><i class="fa fa-clock-o"></i> <span class="post-date updated">', '</span></li>');
but it still shows the published data.
my post is published on the 1st: <
and I updated it on the 7th: <
and the_modified_date() function, displays the published date. am I doing something wrong? how can I fix this? | I think that you are using Parsidate plugin to convert dates to Hijri date. The plugin since the current version(2.2.2) returns the published date for both `the_date` and `the_modified_date` functions. This is a bug that i reported it to them. For now, you can use the wp-jalali plugin instead, that solved the problem for me. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "date, publish"
} |
Does htaccess password keep search engines out?
I had a mishap when a site on my staging server was picked up by Google. I want to devise a foolproof but simple strategy to prevent this from happening again. Would password protecting the entire subdomain with htaccess prevent Google from being able to index a site? | Not really a WP question, but I do this with dev sites. I don't think I can give you an absolute answer as to search engines' behavior, but speaking from experience, adding authentication like htpasswd retroactively would cause an _eventual_ departure from search results. Adding auth proactively has produced effective results for me. The search engine hits the auth, then is left with a 401 error.
You can also try asking Google to in-undex your stuff if you need to. The site needs to be registered in Google Websmater Tools/Search Console. < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "htaccess, search engines"
} |
Update post using json api v2
I'm trying to update a post using the json api Version 2.0-beta13.1. It returns success but doesn't modify the post. I'm doing it from Python but I don't think there should be anything special about that.
import requests
from requests.auth import HTTPBasicAuth
import json
data = {
'title': 'my new title'
}
resp = requests.put(' data=json.dumps(data), auth=HTTPBasicAuth(userid, passwd))
print(resp.text)
I've tried post, put, various fields.. But it just reports success and ignores me. Any suggestions? | I was using requests wrong. This seems to fix it:
resp = requests.request('put', ' json=data, auth=HTTPBasicAuth(userid, passwd)) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugin json api"
} |
Redirect logged in user to somepage on every page view?
Is there a hook that is called everytime a logged in user requests to view any page?
Basically I want to continually redirect a logged in user to a specific page until they complete a requested action. So no matter what page they try to view, I want to be able to redirect them.
Thanks | I would utilize the user meta info and 'wp' hook for this. You can use a function similar to below:
add_action( 'wp', 'wpse69369_special_thingy' );
function wpse69369_special_thingy()
{
if ( is_user_logged_in() && "" == get_user_meta( get_current_user_id(), 'completioncheck', true ) )
wp_redirect( string $location );
exit;
}
}
Then when the user completes the action necessary you can use the following function:
add_user_meta( get_current_user_id(), 'completioncheck', 'yes' );
Info on the user meta functions I used can be found here:
get_user_meta()
add_user_meta() | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development"
} |
woocommerce: get product detail form sku
i have made custom template file in wordpress , now i want to get product detail from product sku , need help how to do it is there woocommerce function to load product detail from sku . | Check this post that provide a method for get product by sku: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "woocommerce offtopic"
} |
Creating table layout in WYSIWYG editor
I am having a design as mentioned in the image.
 has table option, but by default it is disabled in WordPress. You can download plugin, for example TinyMCE Advanced, and enable various and powerful TinyMCE options. Also, you can switch view to text editor and add table in HTML:
<table>
<tr>
<td>Cell</td><td>Cell</td>
</tr>
<tr>
<td>Cell</td><td>Cell</td>
</tr>
<tr>
<td>Cell</td><td>Cell</td>
</tr>
</table> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "editor, wysiwyg, post editor"
} |
Insert Plugin on a custom page
May I know if I can insert curtain plugin on a page. For example, if I edit page `header.php`. How do I want to insert a plugin on that page. The plugin that I want to use is **Huge IT Image Gallery**.
I tried to edit `header.php` and insert the code such as `[huge_it_gallery id="4"]` provided by the plugin, but the image gallery did not appear. Do I need to insert a `<script></script>` or the plugin directory on my `header.php` page.
I am new and still studying on the wordpress development. | do_shortcode Is a function which executes shortcodes in WordPress
In your case you should use it in your header.php file as the following:
<?php echo do_shortcode('[huge_it_gallery id="4"]'); ?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, headers"
} |
Advanced Custom Fields plugin - get text from editor field and save it in a variable
In ACF I added a custom editor field but when I try to save it's text into a variable and output the value with js to the console it gives me an empty string.
Here's my code:
<?php $test = the_field('text'); ?>
And the javascript:
<script>
var v = '<?php echo $test; ?>';
console.log(v);
</script>
I need to get the text value because I need to check if there are list items in it. What am I doing wrong? Or is there a special method for that? If i try to output it directly to the front end...
<?php the_field('text'); ?>
...it works. | `the_field()` is a echo statement use `get_field()` instead.
You can't save echoed value into a variable, for that you may need to use output buffer `ob_start`.In your case `get_field` function should work. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, advanced custom fields, editor"
} |
Variant of the same theme for each page
I have a wp site with seven books, each book has a page, and each page will have the same structure, but differents style ( Each book has his own color guide).
So, what I need is apply a different variant of the same theme for each page...
Is it posible? How should I do it? | The simplest would be to add it to a CSS style.
WP output body classes, which allow to precisely target any specific page with CSS by ID, for example:
<body class="page page-id-7 page-template-default logged-in admin-bar no-customize-support group-blog no-sidebar">
While it's not default I also like to hook into it and add `page-[name]` class for myself.
If your theme is custom you can just work styling into it. If you are using off the shelf theme you should probably create a child theme for it and implement custom styles there. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "themes"
} |
Bootstrap js refuses to load
I've used a small javascript file to create an off canvas push navbar. I loaded the file as described in the Wordpres Codex:
function sidebar () {
wp_enqueue_script('theme-js', get_stylesheet_directory_uri() . '/js/nav-sidebar.js',array( 'jquery' ),$version,true );
}
add_action('wp_enqueue_scripts', 'sidebar');
However, it seems that the only js that is loaded is the nav-sidebar and the bootstrap.js refuses to load. If i remove nav-sidebar.js, bootstrap.js loads just fine. It creates a conflict that i can't solve.
You can find the script i've used here | Expanding @RRikesh comment, you might have enqueued/loaded the `bootstap.js` with same handle `theme-js`. So only one script gets enqueued.
Try to use different handle for example `nav-sidebar`. See the following code. Also it's recommended to use prefix, here I used `wpse`. Also use `get_template_directory_uri` instead of `get_stylesheet_directory_uri()` if it's not a child theme.
function wpse_sidebar () {
wp_enqueue_script('nav-sidebar', get_template_directory_uri() . '/js/nav-sidebar.js',array( 'jquery' ),'1.0.0',true );
}
add_action('wp_enqueue_scripts', 'wpse_sidebar'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "wp enqueue script, twitter bootstrap"
} |
Insert Content Before div#main from the functions.php File
I know WordPress has a filter for targeting the content in the functions.php file:
add_filter( 'the_content')
However, is there a filter to insert content BEFORE ? 'the_content' filter puts content AFTER div#main. I'm looking for something like:
add_filter( 'before_main')
Does a filter like that exist? | The markup surrounding the content is not specified by WordPress, so there is no hook for that.
But you can declare your own hook there. In your template file, write …
<?php
do_action( 'before_content_container' );
?>
<div class="main">
<?php
the_content();
?>
</div>
<?php
do_action( 'after_content_container' );
?>
… and then you can register a callback for that action in your `functions.php`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, filters, hooks, actions, the content"
} |
How to insert multiple images into a single post within a CPT
I have created a `Custom Post Type` to publish multiple images together.
\--->>> title <<<\---
\--->>> image default - thumbnail <<<\---
\--->>> cotent <<<\---
\--->>>images<<<\---
\--->>>images<<<\---
.....
The first three sections (title, image default and content) is the basics. Is ready.
I thought about using `custom metabox` and add each image URL. However, add url by url is nothing intuitive and a lot more work for the user, be it newbie or advanced. Furthermore, the amount will vary pictures can be 1, may be 5 may be 10 and so on....
So, how do I add multiple images within a single post `CPT`?
The Dashboard would look like this:
\--->>> title <<<\---
\--->>> image default - thumbnail <<<\---
\--->>> cotent <<<\---
\--->>> add images<<<\---
How can I do this? Be a plugin or direct in `function.php`. | * * *
## UPDATED
I got it! I made this way, I created a gallery within the wordpress editor. And with foreach, I took the ID of each image and display in the Loop:
<?php
global $post;
$gallery = get_post_gallery_images( $post );
foreach( $gallery as $image_url ) {
?>
<div class="item">
<figure style="margin: 0px !important" itemprop="associatedMedia" itemscope itemtype="
<a href="<?php echo $image_url ?>" itemprop="contentUrl" data-size="1800x1200" data-index="0">
<img src="<?php echo $image_url ?>" class="image" itemprop="thumbnail" alt="">
</a>
</figure>
</div>
<?php
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, images, gallery"
} |
Hide everything on site for visitors except specific page IDs
I have a client who wants to close down access to the entire site, every post, category page, archive etc (while keeping the content), except for three specific pages (Start, about us, contact).
None of the membership plugins seem to address this, only logged in roles? I feel like this is the most simple thing ever, but I just can't seem to solve it.
Edit: Basically, what I'm saying is "if page x, x or x" continue, "else display message". | If you want to show a message, use this code in your `functions.php` file-
function se_236335_hide_content( $content ){
$pages = array( 8, 26, 35 ); // allowed page IDs
if( ! in_array( get_the_id(), $pages ) ){
return 'Message here..';
}
return $content;
}
add_filter( 'the_content', 'se_236335_hide_content' );
If you want a page redirection, use this-
function se_236335_redirect(){
// allowed pages IDs
$p1 = 9;
$p2 = 11;
$p3 = 35;
// redirect location
$location = 9;
if( ! is_page( [ $p1, $p2, $p3 ] ) ) {
wp_redirect( get_permalink( $location ) );
exit();
}
}
add_action( 'wp', 'se_236335_redirect' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "users, user roles, user access, content restriction"
} |
Moving to another host; which tables to move in a database
I'm moving my website to a new host and would like to move only my posts and images to the new site. I don't want to use WP export because I've had bad experiences going that route. I don't want to copy the entire database, just copy the posts and images in the database.
What tables can I copy over?
Thanks, | I never personally tried this, but your images and posts reside in your `{prefix}posts` (wp_posts) table. I would also copy `{prefix}postmeta` (wp_postmeta) over.
So copying over those table should do what you want.
Keep in mind that this won't copy your categories and tags (meta), and your comments (comments) they reside in other tables, you could find those easily they have `meta` and `comments` in their names. Copy those too if you want that. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "database, table"
} |
How to setup 301 redirects for multiple query string URLs?
I have multiple URLs that follow the same pattern like this:
`
Is there a way to perform a 301 redirect to the following URL instead?
`
If I use this plugin, Safe Redirect Manager, is there a way to set that up?
My Server:
* VPS CenterOS
* NGINX | From doing some research, I'd recommend trying out this plugin: Redirection. This plugin allows you to manage 301 redirections.
I played around with the settings and they allows regular expressions which could do the following:
` to `
They provide documentation on how to set it up which can be found here. This is what I've done when creating the rule, try this:
/`
* **Target URL** : `/tags/(.*)`
I was testing this out on a local copy of WordPress and I don't have anything right now that gives me those URL structures. Let me know if that works for you on your end. Again, you can play around with the regular expressions to get it right. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 3,
"tags": "redirect, urls, nginx"
} |
'child_of' in get_posts not working
I don't know why, but for some reason neither `parent` or `child_of` are being accepted as arguments in `get_posts` that I'm using a `foreach` loop.
$sidebarReviews = get_posts(array(
'child_of' => get_ID_by_slug('testimonial-reviews'),
'orderby' => 'rand',
'posts_per_page' => '6',
'post_type' => 'page'
));
Note: the `get_ID_by_slug` is a custom function I have just to translate slugs into page IDs. This is working correctly.
However, when my foreach runs, it seems to pick up every page that's in my Wordpress database.
What's happening? | I think you confused arguments with those for _term_ functions. :)
For posts the correct argument is `post_parent`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "get posts, php"
} |
Understanding apply_filters
I get the same results with these to lines, so what does `apply_filters` do?
Line 1 : echo $instance['title'];
Line 2 : echo apply_filters('widget_title', $instance['title']); | Well, `apply_filter` creates a global filter hook which can be used dynamically all over the system. Which gives you the ability to filter the content of the `$instance['title']`, means you can over ride the content as well as can modify the content. Here is the example-
add_filter( 'widget_title', 'widget_title_to_uppercase', 10, 1);
function widget_title_to_uppercase( $content ){
$content = strtoupper($content);
return $content;
}
Now all the widget title will be uppercase. So with this filter hook you can filter the `widget_title` from any where the WordPress system. But with the `$instance['title']` it is not possible. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "plugins, plugin development"
} |
WP_Query returns posts_per_page + 1 every time
I have a simple `WP_Query` where I am intending to only get the latest 4 posts returned:
<?php
$query = new WP_Query([
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 4,
]);
var_dump(count($query->posts));die; // Returns 5 instead of 4
?>
`count($query->posts)` is 5 every time. Why isn't it 4? | I've seen this happen when you have sticky posts. Try excluding them, like this:
<?php
$query = new WP_Query([
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 4,
'ignore_sticky_posts' => true,
]);
?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp query"
} |
How to get a list of bundled products using wp_query in woocommerce
I want to fetch a list of bundled products using WP_Query.I have used the following
$args = array(
'post_type' => 'product',
'posts_per_page' => 9,
'orderby' =>'date',
'orderby' => 'rand',
'meta_query'=>array(
array(
'key'=>'_thumbnail_id',
)
)
);
$loop = new WP_Query( $args );
How can i pass an argument to get bundled products? Can anyone help please..
Thanks | You should be able to do it using 'tax_query':
'tax_query'=> array(
array(
'taxonomy' => 'product_type',
'field' => 'slug',
'terms' => 'bundle',
),
), | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, wp query, loop, woocommerce offtopic"
} |
update_user_meta() not working
i'm having a trouble with Wordpress, with the function `update_user_meta()`
I'm trying to update or add a new custom meta value for the user, who already have the custom meta working on the edit profile. But when i do the function `update_user_meta()` outside the `edit-profile.php`, just didn't work for me.
I have a page like a page of contact where the form will edit the custom metadata of the profile, in the front side of the wordpress like a normal page of wordpress, but when he submit the form, he just don't update, here is my code:
when the user submit:
function update_termini() {
$user = wp_get_current_user();
$userData = array();
$userData['checkbox'] = intval( $_POST['custom_user_fields_checkbox'] );
update_user_meta( $user, 'custom_user_fields', $userData );
}
add_action('edit_user_profile', 'update_termini'); | `wp_get_current_user()` returns an object. `update_user_meta( $user_id, $meta_key, $meta_value, $prev_value` ) accepts `user_id` as first parameter. Use the following code to get user ID from `wp_get_current_user()`
update_user_meta( $user->ID, 'custom_user_fields', $userData ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "user meta"
} |
Menu on mobile version doesn't collapse after choosing menu item
I currently have a one page site. On the mobile version when the menu expands and i choose an item the menu stays open while the page moves to correct anchor but it is blocked by the menu. is there a code or snippet to insert to make the menu collapse after an item is selected?
Thanks | Add this jQuery to your theme:
(function($) {
$('.nav-menu a').on('click', function(){
if ( $(this).data('toggle') !== 'dropdown' ) {
$('.main-menu .close-button').click();
}
});
})(jQuery);
It will close the menu when a nav link is clicked. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "menus"
} |
Find posts by related taxonomy field
I have "projects" (a custom post type), with many custom fields (created via ACF), one of which relates the project to an "artist" (a custom taxonomy).
Finally, I have "products" that also use the custom taxonomy "artist".
On a product page, I would like to fetch the latest "project" that was related to that same artist.
Here is the code that I believe should work, but it returns an empty array (it should return three projects).
$projects = get_posts(array(
'post_type' => 'project',
'meta_query' => array(
array(
'key' => 'artist', // name of custom field
'value' => '"' . $artist->term_id . '"',
'compare' => 'LIKE'
)
)
));
I've double-checked that $artist->term_id returns a correct value: it does. | You're meta querying on serialized data. I mean the `artist` from `'key' => 'artist'` is serialized. That's why your meta query hasn't work. So here is my possible solution-
$projects = get_posts(array(
'post_type' => 'project',
'meta_query' => array(
array(
'key' => 'artist', // name of custom field
'value' => '"%' . $artist->term_id . '%"',
'compare' => 'LIKE'
)
)
));
With this wild cards `%` on both side of your `$artist->term_id` will work I think. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "meta query"
} |
How do I demote a menu item in the admin menu?
Many plugins create a top-level item in the admin menu, even though there is no need. (There is discussion of when to create a top-level item and when to create a sub-item on the codex.) This can lead to a cluttered admin menu:
 {
remove_menu_page( $menu_slug );
}
add_action( 'admin_menu', 'custom_menu_page_removing' );
Here you'll get a documentation. Please follow that.
Then you need to add the page to settings by using `add_options_page`. Here is
add_action( 'admin_menu', 'my_plugin_menu' );
function my_plugin_menu() {
add_options_page(
'My Options',
'My Plugin',
'manage_options',
'my-plugin.php',
'my_plugin_page'
);
}
And for adding to **Tools** menu use `add_submenu_page`.
The documentation is here. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "admin menu"
} |
How to list child categories in custom category template?
I'm trying to create a custom category template that will display a list of the current category's child categories. Besides the name and link to the category I also want to add a thumbnail and the category description. I tried the following code but it didn't return anything:
<?php
$catid = get_category(get_query_var( 'cat' ));
$termchildren = get_term_children( $catid, 'category' );
echo '<ul>';
foreach( $termchildren as $cat ) {
$term = get_term_by( 'id', '$cat', 'category' );
echo '<li>'.$term->name.'</li>';
}
?>
I've left out the other parts of the html list at this stage as I'm just trying to get it to work and will add them in later. | This piece of code will return you the child categories of a parent-
$cat = get_category( get_query_var( 'cat' ) );
$cat_id = $cat->cat_ID;
$child_categories=get_categories(
array( 'parent' => $cat_id )
);
Just pass the category id to `$cat_id` variable which children you want. After that you can design or print those as you want. Example-
foreach ( $child_categories as $child ) {
// Here I'm showing as a list...
echo '<li>'.$child ->cat_name.'</li>';
}
Hope this is gonna help. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "categories, customization"
} |
how to get random post id by using post type
I need to get a post ID's random manner...
Something I tried like this,
$args = array( 'post_type' => 'adzones');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$id = the_ID();
echo do_shortcode("[pro_ad_display_adzone id=".$id."]");
endwhile;
Here I'm try to display an add post inside the loop but it won't work for me...
And also It retrieve only all post ID's in asc order...
How should I do this..someone help me..
Thank you, | As far I understood you want to set the value of `$id` randomly from `adzones` post type post ids. I hope this helps you-
$args = array(
'orderby' => 'rand',
'posts_per_page' => '1',
'post_type' => 'adzones'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$id = get_the_ID();
echo do_shortcode("[pro_ad_display_adzone id=".$id."]");
endwhile; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "posts, post type"
} |
Uninstalling a plugin: delete all options with specific prefix
### Objective
As all plugin developer, I want to delete all options that begin with the same prefix.
### Backstory
I've developed a plugin that stores data in the options. When the user uninstalls the plugin, the `uninstall.php` in the plugin executes the following code:
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
delete_option( 'myplugin_some_opt_1' );
delete_option( 'myplugin_some_opt_2' );
delete_option( 'myplugin_some_opt_3' );
delete_option( 'myplugin_some_opt_4' );
Since all of the options start with `myplugin_`, I want to implement a wildcard. Logicall, I assume that it would look something like this:
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
delete_option( 'myplugin_*' ); | I've found out another alternative by using the `wp_load_alloptions()` function to get all of the available options, then `delete_option()` for every option that has the `myplugin_` prefix:
foreach ( wp_load_alloptions() as $option => $value ) {
if ( strpos( $option, 'myplugin_' ) === 0 ) {
delete_option( $option );
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "php, plugin development, uninstallation"
} |
Save Textarea on Wordpress Frontend
So I have absolutely no idea where I should start on this, other than obviously creating a textarea.
Basically I'm upgrading a platform and on the previous platform, everything ran through php frames. Because of this, I could stick a textarea in one of the frames that was constantly showing and when people switched pages, the content would still be there on that person's computer until they reloaded the site or something like that.
What I need is to basically duplicate this. Now, I know I can't do frames, but I was thinking, what if I could add a save button that would save the content of that box. Of course, that would generally save it globally for all users, which is not good since there will likely be times where multiple people will hit save at the same time and someone will lose their content. So is there a way that I can save this content locally, or maybe save it only for the user who pressed save? | Found my answer here: <
Pretty much exactly what I wanted. I may try to work this so that it autosaves, but other than that it is working perfectly for now. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization"
} |
Adding Filter Conditionally Per Page ID
I've created a function to add a class to the body, however if should only apply to a single page ID. This normally wouldn't be a problem, but it is breaking the layout for other pages.
**Filter Function**
add_filter('body_class','add_blog_to_body_class');
function add_blog_to_body_class($classes) {
$classes[] = 'blog';
return $classes;
}
**My Condition (that isn't working)**
function add_blog_to_body_class($classes) {
$classes[] = 'blog';
if ( is_page('ID') ) {
return $classes;
}
}
I've wrapped the entire function, the declaration, the `add_filter` hook, and everything without luck.
How can I have this function work on a single page ID? | It's important to **always return the value** in filter callbacks, otherwise it's like adding the `__return_null()` callback.
Here's an example that adds the `blog` class only to page with ID 40:
add_filter( 'body_class', 'add_blog_to_body_class' );
function add_blog_to_body_class( $classes )
{
if ( is_page( 40 ) )
$classes[] = 'blog';
return $classes;
} | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "filters, conditional tags"
} |
Best method to add style sheets into child theme?
I created a Twenty Fifteen child theme and wondering what is the best method to add style sheets into the child theme? Should I use enqueue script in `functions.php`, or add directly in `header.php`? | Firstly, never add the stylesheet on `header.php` unless you have to. It is not the WordPress convention.
Secondly, adding stylesheet to `header.php` will cause certain problem like dependency hierarchy. Cause when you install any plugin and if it has its stylesheet then the dependency hierarchy is automatically managed by WordPress system by `wp_enqueue_scripts` hook.
Thirdly, by using `wp_enqueue_scripts` hook you can use WordPress default scripts and stylesheets which is kinda messy if you proceed to use it in the header.
Fourthly, (I'm not 100% sure) caching can be a problem if you use stylesheet on `header.php`.
And all those rule are applicable for themes as well as child themes and plugins. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "child theme"
} |
is it ok to dequeue default parent stylesheet from custom page templates in child theme?
I have created twenty fifteen child theme and am using enqueue to add
styles into it.
I have an HTML layout of a page and i want to convert it into a custom WordPress page template but i have a doubt that if i don't remove default parent style sheet which is inherited by my child theme then my template will not look same as HTML template .
So is it fine to dequeue default parent style from some pages ? you guys also do this for creating custom template from HTML ? | Yes, if you need to dequeue parent stylesheet, go ahead. No problem with that. From the point of programming there is no problem. But as a developer I would suggest to override the stylesheet from your child theme. In the end your thinking matters. There are various ways to accomplish anything. Have fun ! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "child theme"
} |
Redirect home to another page with htaccess
I have a page which is called `/home` and I would like to make my `.htaccess` redirect it to `/homepage` which is the actual page that I want to show.
My `.htaccess` has the following:
# Switch rewrite engine off in case this was installed under HostPay.
RewriteEngine Off
SetEnv DEFAULT_PHP_VERSION 55
DirectoryIndex index.cgi index.php
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
What do I have to add whenever a user tries to go to ` to redirect them at ` | Add the following to your `.htaccess`, in between the `<IfModule mod_rewrite.c>`:
RedirectMatch 301 /home /homepage
Redirect 301 / /homepage
However, as Omar suggested, you can change your homepage through your [dashboard] by doing the following:
* Go to **Settings** > **Reading**
* Under **Front page displays** , select **A static page (select below)**
* Next to **Front page:** select the page for your new homepage from the dropdown menu
* Click **Save Changes**
![Change the front page settings in WordPress]( | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "redirect, urls, htaccess, rewrite rules, homepage"
} |
wordpress API for android app
I'm looking for a plugin that convert everything a user can do on browser into JSON because I want to use this data for an application on android and also I want it to be compatible with woocommerce plugin. I found two plugins `JSON API` and `WP REST API` but my question is "do they support user login and woocomerce?"
is there any other plugin ? | Yes, `WP REST API` supports user authentication. With this plugin you can use **OAuth authentication, application passwords, or basic authentication**. Read this. Here you'll find complete documentation.
For `JSON API` there is a plugin called `JSON API Auth`. Here you'll get it. By using it you can implement authentication with `JSON API`.
And yes, as far I know both of them supports `WooCommerce`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "json"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.