INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Displaying Only Certain Tags in Loop **What I'm trying to do is alter the loop across my site so it will check the site URL so it will know which tag to display.** For example, if I give some posts the tag "golfclubs", I want it to work something like this: if ($_SERVER['HTTP_HOST']=="www.golfclubreviewdomain.com"){ // code here to display only the "golfclubs" tagged posts } In case the code above is incorrect for what I want, I just want to check the current domain to see if it is < and if so, display the posts that are tagged with "golfclubs". I would like this change to work across all themes, so I want to change this at highest level if possible so it will affect homepage, categories, etc. Is there a core file that I can use that will never be updated when I upgrade wordpress? And my final question, what change do I make to display more than 1 type of tagged post? maybe something like "golfclubs" and "general"?
* Create a must-use plugin. * Put it in `<docroot>/wp-content/mu-plugins/selective-posts.php` * Following should be the code in `selective-posts.php` to filter specific posts. function golfclubs_tag( $query ) { if ( $_SERVER['HTTP_HOST'] === 'www.golfclubreviewdomain.com' ) { $query->set( 'tag', 'golfclubs' ); } } add_action( 'pre_get_posts', 'golfclubs_tag' ); This way it would filter all the queries across the site for specific domain and it would filter the posts with specific tag. If you want to add another tag in the query, you can edit the above code as follows: function golfclubs_tag( $query ) { if ( $_SERVER['HTTP_HOST'] === 'www.golfclubreviewdomain.com' ) { $query->set( 'tag', 'golfclubs,general' ); } } add_action( 'pre_get_posts', 'golfclubs_tag' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, loop, tags" }
How to display username and password after registration When a new user registers for a new account, WordPress sends an email with the login information as usual. The password is auto-generated and stored securely in the WP database and the registration is handled by MemberMouse. MemberMouse defers all user authentication to WP's built in system so they don't do any of the generation themselves. What I'd like to do is route this new user to a Thank You page that displays some information like instructions on what to do next and will also display the username and generated password on this HTTPS page that allows them to more easily login since emails often end up in the spam folder. Is there an easy way to do this?
No as it will be insecure to do it. Being able to display the password to the user means that you store it as a plain text somewhere which is a big no no. Emails ending in spam should not be relevant here as you should not send passwords in email. (sure you can hack something to make what you want but the system is not built to support such a thing)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "login, authentication" }
How to add a tag above a category post that displays the category name in Wordpress I am wondering how I can display the category name on top of each article on this page. For example, each of the articles on this page are from multiple categories. Preferably, the category name would appear above the article title and below the photo. I tried some of the settings in the Scene theme to no avail. I am guessing I'll have to jump in the PHP and code in the action to display the category name. Here is the URL for the website: < Thanks.
There is `single_cat_title()` that should do what you want. > ## Description > > Displays or returns the page title if a category or tag archive is queried. Therefore, the function can be used only outside the loop.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "categories" }
scrolltop always 0, can't trigger script While trying to add a jQuery trigger on scroll script to my child theme, I noticed it never triggered even though it was added. However after trying to figure out why the script wasn't working I used `document.body.scrollTop` to find it always returned a value of `0` despite having a larger scroll height. I tried the same thing on the unmodified parent theme and found it also always returned me a `0`. So I'm assuming there is some style or script that is hijacking it. I've tried to hunt it down but no luck as of yet. Is there anyway I can reset the scrolltop property via css / javascript or trigger my script on a different scroll trigger?
I guess `body.scrollTop` is deprecated in strict mode. Please use `documentElement.scrollTop` if in strict mode and `body.scrollTop` only if in quirks mode. So I would suggest you to use `document.documentElement.scrollTop`. also let us know when are you using this statement? show us full code and your console error if possible Please try the below code edited with respect to your comment code and let us know what you see in console. jQuery(document).ready(function ($) { jQuery(window).scroll(function(){ var ScrollTop = jQuery(window).scrollTop(); if (ScrollTop > 100) { jQuery( ".site-header" ).addClass( "scroll" ); console.log("above 100"); }else{ jQuery( ".site-header" ).removeClass( "scroll" ); console.log("below or equal to 100"); } }); });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, jquery, events" }
How do I load custom scripts and styles for a page? Different pages often need different set of scripts and styles for them. I use functions.php and construction like this to load scripts and styles: function load_assets() { wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/styles.css'); wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js'); } add_action( 'wp_enqueue_scripts', 'load_assets' ); I know I can put some condition here like this: is_page() but is there a better way? Suggestion: Can wp_register_script() be used to target specific pages?
Yes, you may add conditional tags to the `wp_enqueue_scripts` action. See the examples below: function load_assets() { wp_enqueue_style( 'styles', get_template_directory_uri() . '/css/styles.css'); // loads on any 'page' post type if( is_page() ){ wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js'); } // only loads on the page with a slug of 'home' if( is_page('home') ){ wp_enqueue_script('home-js', get_template_directory_uri() . '/js/home.js'); } } add_action( 'wp_enqueue_scripts', 'load_assets' ); For other examples of `is_page()` usage, see the codex page: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "pages, wp enqueue script, wp enqueue style, scripts, css" }
Twenty Fifteen Premium Theme I am wondering if GPL License allow us to make premium theme from Twenty Fifteen Wordpress. Can We customize such themes and sell? Please let me know. Thank you!
You might want to look at what the GPL License entails. This Wikipedia article does a pretty good job of explaining:< "Any licensee who adheres to the terms and conditions is given permission to modify the work, as well as to copy and redistribute the work or any derivative version. The licensee is allowed to charge a fee for this service, or do this free of charge." Hope that helps
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "themes, premium" }
How to show the amount of post that have on the site? How can I make a code show the number of posts you have on my site, adding all fair categories??
Using a query could give you easier customization without having to use SQL directly. $posts = get_posts( array( 'post_type' => 'post', 'post_status' => 'any', 'numberposts' => -1, 'fields' => 'ids', )); $total_count = count( $posts ); print_r ( $total_count );
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "count" }
Call a custom field in an audio shortcode? I'm attempting to call a custom field in an audio shortcode. The field I'm calling, _enclosure_ , defines MP3 files that are associated with my respective posts. I'm using the PHP template editor in Wordpress. Here's what I have. <?php echo do_shortcode('[audio src="enclosure"]');?> I would like to insert the following code in place of the word "enclosure." <?php echo get_post_meta($post->ID, 'enclosure', true); ?> I either get the code displayed as text or nothing at all when I paste these snippets together. What am I missing?
Try using PHP's string concatenation: <?php echo do_shortcode('[audio src="'. get_post_meta($post->ID, 'enclosure', true) .'"]');?> or: <?php $enclosure = get_post_meta($post->ID, 'enclosure', true); echo do_shortcode('[audio src="'. $enclosure . '"]'; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "custom field, shortcode, audio" }
how to use wp_redirect inside a function I have the following action and function. Ultimately i'm trying to get access to value $processArtwork in my template. One option is pass the value via the querystring. However the following results in **"Warning: Cannot modify header information - headers already sent by (output started at /home/xxxxxx/europeanpaintings.rpc-staging.com/wp-includes/formatting.php:1021) in /home/xxxxx/mysite.com/wp-includes/pluggable.php on line 1228"** add_action('init', 'process_artwork'); function process_artwork(){ if(isset($_GET['ss-process'])) { $newUrl = "/process-artwork/?processedArtwork=56"; wp_redirect( $newURL ); exit; } }
You do not get that error because it runs inside a function, but because the headers have already been send. This means your server already has send some information about the page to the client, thus is it unable to change it's headers (headers are the first thing that gets send). This mostly happens after something gets echo'ed. There are a few things you can do to prevent this from happening: * Choose another event that gets triggered before the headers are send * Remove any echo'ed text or HTML before the redirect * Check if there is no whitespace (spaces, enters, tabs) between the the start of your file and the `<?php` tag. * Change your server configration to send the headers later (this can be tricky or inpossible).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp redirect" }
Display Selected themes to user in admin for wordpress multisite I have created a wordpress multisite instance and i am able to create new site creating a normal user with subscriber role. I have 3 themes by default in the Appearance > Themes section (i.e. Twenty Fifteen, Twenty Fourteen, Twenty Thirteen). But, i want my site users who create new sites to be able to access only two themes from their site admin panel. Let's say they should get access to Twenty Fifteen and Twenty Thirteen in their site admin panel. Can any one help me into this?
you have to Network Disable the theme. codex > Disabling a theme in the Network Admin Themes Screen does not prevent that theme being used by a site. It only prevents the theme being listed in the available themes list when selecting a new/different theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite" }
jQuery datepicker not showing on admin menu Nothing happens when I select the datepicker field. This is the code for the field: <input id="sticky_date" name="sticky_date" class="datepicker hasDatepicker" type="text"> The javascript jQuery(function() { jQuery( '.datepicker' ).datepicker({ changeMonth: true, changeYear: true, yearRange: "-100:-10" }); }); The include code add_action('admin_head', 'admin_datepicker'); function admin_datepicker() { wp_register_script( 'pub-datepicker', get_template_directory_uri().'/js/datepicker.js', array( 'jquery-ui-core', 'jquery-ui-datepicker' ), false, true ); wp_enqueue_script('pub-datepicker'); } I'm not really sure if I'm missing something, there's no error on the js console, nothing happens
I found the problem. My input field was declared like this: `<input id="sticky_date" name="sticky_date" class="datepicker hasDatepicker" type="text">` It turns out that the `hasDatepicker` is assigned by the js when the date picker popup is shown, so when I clicked it nothing happened because it basically "thought" that the popup had been shown already. I simply changed it to: `<input id="sticky_date" name="sticky_date" class="datepicker" type="text">`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, wp admin, admin menu, jquery ui, datepicker" }
Redirect after delete post in Frontend I use the following link to delete a post in the frontend of wordpress: <a href="<?php echo get_delete_post_link( $post->ID ) ?>">Delete Post</a> This works fine. But after i delete the post its just showing a blank page of the index.php. I want to redirect the author who deletetd the post to a category site like /post-archive. Any idea how i can do that? Thx for your help and best regards.
I got a little bit more into this topic and found this solution which works perfect for me. 1 Add this code to functions.php: // Delete post function delete_post(){ global $post; $deletepostlink= add_query_arg( 'frontend', 'true', get_delete_post_link( get_the_ID() ) ); if (current_user_can('edit_post', $post->ID)) { echo '<span><a class="post-delete-link" onclick="return confirm(\'¿Are you sure to delete?\')" href="'.$deletepostlink.'">Borrar</a></span>'; } } //Redirect after delete post in frontend add_action('trashed_post','trash_redirection_frontend'); function trash_redirection_frontend($post_id) { if ( filter_input( INPUT_GET, 'frontend', FILTER_VALIDATE_BOOLEAN ) ) { wp_redirect( get_option('siteurl').'/page-deleted-post' ); exit; } } 2 Call the function on youre template file (single.php or whatever): echo delete_post();
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "front end" }
How can I create a rearrangeable list of items like OptionTree offers with the Theme Customization API? I have a theme that currently uses OptionTree, I'd like to move to the WP Theme Customizer API. In OptionTree I can have a list of items that can be edited and drag and drop rearranged. Is there a way to accomplish this with the WordPress Customizer API?
I suggest you take a look at the Kirki toolkit: < It has a "repeater" field that should do what you need. It's still under heavy development and for the time being I've only added the ability to use a few field-types with it, so I guess it depends on what exactly the data you want to add & re-arrange is, but it's worth a look.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme options, theme customizer, api, plugin option tree" }
Mobile version issue when domain forwarding with masking Setup domain to forward to server but when setting the host to forward with masking the mobile version is not loading correctly. When setting domain to redirect without masking (to the IP) the site loads correctly Screenshots here - Top image is without masking (not IP in search bar) and bottom image is with masking Don't know if it makes a difference but site is setup as below **Site Settings** ![Site Setting](
OK solved. Issue was that domain was setup to redirect to IP. What I did that solved the issues was to edit the A record to point to the site IP and removed the domain forwarding. Then was able to set the Wordpress and Site URL to the domain (as suggested in other posts) and all is working fine now
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "url rewriting, mobile, domain" }
Create a custom page URL I have and `archives.php` file developed which I want the user to be able to access. How can I register a new page so that when a user types `mysite.com/archives` he goes to this page?
Make `archive.php` template . And read this: Category Templates
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "php, pages, archive template" }
How often do you need to register_post_type? Assuming you write a plugin and hook into activation / deactivation to register_post_type is that good enough? Or do you need to do it every init? I'm looking for perf boosts and I want to reduce unnecessary calls. GenerateWP uses `add_action( 'init', 'custom_post_type', 0 );` so that might be as early as I might want to register it. **FINDINGS** * @s-ha-dum: > `register_post_type` needs to be called on every page load > > The `post` data itself is kept in the database, but the registration tells the PHP what to do with it. * @pieter-goosen: > Build in types are actually registered twice on every page load (due to localization that is only available on `init`)
`register_post_type` needs to be called on every page load-- `init` seems to be fine and is the hook used in the Codex sample. The post data itself is kept in the database, but the registration tells the PHP what to do with it. Most of the post type information-- the `$labels`, the `$args`\-- are not kept in the database to my knowledge (though I would agree that there _might be_ an argument for doing so), so without that registration code Core doesn't really know about the post type. You can pretty easily test this yourself by registering the type and then commenting the code.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "custom post types, plugins, plugin development, hooks, performance" }
Theme Customizer - Text without a setting (a comment or <p> tag) In the Theme Customizer, is it possible to just have text (for example a comment, or a HTML `<p>` tag with text), or a setting that has no type (but a title of `Text I need to display`). For example, I may want to say - `Go to XXX to do this` at the bottom of a section, or `Find out more in the documentation` I know you can have descriptions on settings but that is not what I want (unless the setting itself is invisible).
If I understand the question right, the easiest way to implement this now is to create a new control type that doesn't actually render any input but rather just displays your desired text. Controls have to have an associated setting, so you can register a setting with a custom type of `noop` so that it will not have any effect. Give the control a high priority so it will appear at the end of the section. A more elegant solution would be to create a custom section that has this end matter as part of its template. Unfortunately, the `ul` is currently expected to be a direct descendent of the section container, so this is problematic.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme customizer" }
Solution dealing with Child Theme / Parent theme functions This week I was struggling a bit customizing an exsisting theme for a client. To prevent the theme from being overwritten each update I created a child theme. This allowed me to cusomize most of the files that handled templating. The function which loaded additional stylesheets and js libraries was pluggable and could be overwritten. The biggest problem I faced was to overwrite some of the core functions of the theme. These were not pluggable (did not use the if(!function_exsisits()) statement) and didn't use a hook or filter. Calling the same core function from the child theme functions.php or a custom plugin threw a fatal error (function cannot be redeclared).
My solution to this issue was to create a custom plugin with copies of the core functions needed to be overwritten. I gave these functions custom names so I could call them from the template files in the Child Theme directory. Now I could add my own code and modifications and leave files with the core theme functions intact. This creates some redundant code, but now I can use a child theme and 'overwrite' core theme functions until the theme author makes the original core functions pluggable.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, child theme, pluggable" }
Custom css author role I need a code snippet to load css (extra style sheet?) when a author is logged in. This is for a custom dashboard and post "page". ![enter image description here]( The screenshot is what i mean by post page. I want to hide stuf by css for only authors. Things within the red circles are things i want to hide.
If a user is not logged in then admin_head probably won't run. So let's just check their capabilities. function my_custom_admin_head() { if ( ! current_user_can( 'have-fun' )) : ?><style> #welcome-panel{display: none !important;} #wp-content-editor-tools{display: none !important;} </style> <?php endif; // cant' have-fun } add_action( 'admin_head', 'my_custom_admin_head' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, author, admin css" }
Theme Customizer - Hide / grey out settings based on other setting Using the Theme Customizer, is it possible to hide / grey out options based on other options? For example, I have a button. There are 3 settings related to the button: * Is it shown (checkbox) * Text inside button * Link location If the button is not shown (i.e. unchecked), could the other 2 options be hidden / disabled in some way? There is no point being able to customize something that is hidden
Yes. What you are looking for is the control's `active` state. This can be set in PHP via a control's `active_callback`. For more details, see: < <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme customizer" }
Woocommerce hook after creating order? I am looking for a hook which will be triggered after someone submit checkout form and order placed ( no matter he made the payment or not ) . I tried `woocommerce_new_order` But it's not working.
I found the solution. An old order already exists in my order list. So when I am adding new items in order, woocommerce just updating my old unpaid order. So I use `woocommerce_resume_order` action too. Now it's fine.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 12, "tags": "plugins, woocommerce offtopic" }
Wrong slug on blog page <?php global $post; $post_slug=$post->post_name; ?> This code is used after `<head>` and before `<body>` and is supposed to get current page's slug. It works great, however it will get the _slug of first blog post_ when on _"general"_ blog page. Example: * Blog url: `www.my-site.com/blog/ ->` slug in admin area is set to `blog` * Blog post url: `www.my-site.com/post-1/ ->` slug in admin area is set to `post-1` Code echoes `post-1` for both. **Any ideas?**
> This code is used after `<head>` and before `<body>` and is supposed to get current page's slug. It works great, however it will get the slug of first blog post when on "general" blog page. `$post` is going to be set to the first post in the Loop when the page loads. On "page" pages with only one post in the Loop that is going to be the page data you expect. On archive pages it will be the first post in the set of posts on the page. This is what appears to be happening. You can't trust `$post` explicitly like that-- that is, without understanding exactly when it is set to what. (Most loops, even secondary ones, will alter this variable as well) To get the page data itself you need `get_queried_object()` but be careful with that too as it will be different on various types of pages-- sometimes a post object, sometimes a user object, sometimes `null`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "slug" }
Get Comment With Meta value I need get all comments of a post including of the meta value.. for eg. i need all comments fields + a meta value. i tried the following code to get but.. its not working $args = array( 'status' => 'approve', 'type' => 'comment', 'post_id' => '99', 'post_type' => 'product', //'count' => true, 'meta_query' => array( array( 'key' => 'comment_rating_avg_key', 'compare' => 'EXISTS', ), ), ); $comments_query = new WP_Comment_Query; $comments = $comments_query->query( $args ); var_dump($comments); Do i need to write a custom query to get it ? or it can be done using default WP functions ?
`WP_Comment_Query` doesn't pull comment meta. You can search by comment meta but the query doesn't return that data. You could easily check this yourself by looking at the Codex. You need to loop over the results and run `get_comment_meta()`, or essentially do the same via a filter on `the_comments`. It is also possible to add to the data returned by filtering the "fields" clauses: function add_cmeta_wpse_212423($clauses){ // var_dump($clauses); global $wpdb; $meta = "(SELECT meta_value FROM {$wpdb->commentmeta} WHERE ( comment_id = comment_ID AND meta_key = 'test_comment_meta') ) as test_comment_meta"; $clauses['fields'] .= ', '.$meta; return $clauses; } add_filter('comments_clauses','add_cmeta_wpse_212423'); I created a subquery. You could create a `JOIN` as well.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "comment form, comments" }
Wordpress Redirects on Install I'm having problems when trying to install wordpress on subdomain. I've downloaded the arhive from wordpress.org, unzip it on root folder and when trying to install it says ![enter image description here]( I found and tryed several solutions like * creating a htaccess file * clearing cookies * checking/repairing database (even if no table created) * correct file permission Any other ideas?
The problem was created by some code in the htaccess from root. So: To present exactly my configuration: I have \- < with file directly in the root of my hosting. I know this may not be a best practice and i'll change this. Subdomain i was trying to set was in a folder which was along site my maindomain files. * wp-admin/ * wp-includes/ * wp-content/ * s/ * .htaccess On the main site i had install a securrity plugin from ithemes security which was somehow restricting me to install wordpress on a subdomain The solution i chose was to backup and temporarily remove .htaccess from the root to install my wordpress. Next step is to move my main site on a subfolder to prevent future problems like this. I leave this here in hope others how get this error to find it. In case my response is messy don't hessitate to suggest and edit or to contact me. Thanks stackexchange
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "loop, admin, installation" }
how can I put an image in a post with original size whenever I put an image into a post, it always appears in smaller size than original, only after clicking on the image it opens in full size, how can I manage to post original size images in post?
In the Attachment Display Settings there is a size dropdown. Set it to 'FULL SIZE' when you add your image. ![]( ![](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, images" }
Creating a new page template ## Problem I have a template and I want to add new page to my theme for example about. I rename file to `template-about.php`. Also added comments into template: <? /*Template Name: About Us*/?> However, in admin panel do not showing this page. I've read the Theme Handbook on Page Templates
Try this instead: <?php /** * Template name: About Us */ WordPress could be finicky about the short tags (`<?` vs `<?php`) and comment formatting - shouldn't be, but better safe than sorry. Also, make sure that you have the Screen Option to display Page Attributes turned on and that you're on Add New **Page** , not Post: ![image showing Page Attributes](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "page template" }
how can I check if I have sitemap? maybe it's a very stupid question but I'm just getting into wordpress and I installed a plugin `Google XML Sitemaps` and activated it, but I'm not quite sure that it really provides me with sitemap.xml how can I check that? when I go to mywebsite.com/sitemap.xml I can see site map information, so I guess it works?
Yes. Then it works. Add a new post and see if it changes. You can submit your sitemap to search engines but they will eventually pick it up regardless. Just give it time to see results -- it's not instant. Use Google Console < to make sure it's getting picked up.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "sitemap, google xml sitemaps" }
Icon font not working on subdomains of multisite I have a multi site installation consisting of the main domain and various subdomans. The domain and subdomain all use the one theme however the icon font of the theme doesn't display/load an any of the subdomains. Why are subdomains of my multi-site network failing?
# The problem: Console log: > Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at xxx. (Reason: CORS header 'Access-Control-Allow-Origin' missing). # The solution: Add the following header to your .htaccess file: # # Allow icon font to load on subdomains of WordPress multisite install. <FilesMatch ".(ttf|otf|woff)$"> Header set Access-Control-Allow-Origin "*" </FilesMatch> ...before: # END WordPress
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "multisite, subdomains, icon" }
Displaying a form for filtering in custom post type listing In the UNU website under the Experts section (< there's a form where you can filter the experts by their institute and expertise area. This is what it looks like: ![enter image description here]( I understand that the experts are stored in custom post types "expert". But I don't understand how the search form is built so that users can filter experts by selecting their institution and research topics? Specifically: * How to build data structure into the `Expert` type, i.e. how to link an expert with attributes like "institution" and "research area"? * With the above data structure built, how to include a filter for `Expert` listing as shown in the screenshot above? I would appreciate if you could explain the general idea how it's implemented; or is there a plugin so I don't have to reinvent? Thank you.
> How to build data structure into the Expert type, i.e. how to link an expert with attributes like "institution" and "research area"? **Answer** You may use Taxomonies in wordpress, to add extra level od categorization of your posts. In your example, you may register `Institution` and `Research area` taxonomies for your `Experts` custom post type. > With the above data structure built, how to include a filter for Expert listing as shown in the screenshot above? **Answer** You may use an ajax call to pass the filter criteria and receive related experts from the server.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types" }
How can I get the permalink of a page on which shortcode has been used I want to redirect users to a page on which a particular short-code has been used after they login. So basically I want to know how can I get the permalink of that particular page on which my plugins specific short code has been used?
I think that the very best approach would be to store that page on a option. Anyway, if you want to get the pages where a shortcode has been used, you can use the search parameter (`s`) of `WP_Query` class (or `get_posts()` function). Basically, this parameter performs a `LIKE` query, so it could be useful to search for shortcodes like this: $args = array( 's' => '[myshortcode', 'post_type' => 'pages' ); $pages_with_myshortcode = get_posts( $args );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, shortcode" }
How to modify single.php in a child theme? My WordPress site uses a child-theme (of the default twenty-sixteen) and now I would like to insert a new line into the `single.php` file. I know that it's better to use the `functions.php` file of the child-theme than inserting the new line directly into the parent theme's `single.php` file. (Correct me if I'm wrong.) I would be grateful if somebody could show me how to do it properly. I would like to insert this line <div class="fb-comments" data-href="<?php the_permalink(); ?> " data-numposts="5"></div> into the <div id="primary" class="content-area"> element, right above the closing </main> tag in the `single.php` file.
> your child theme can override any file in the parent theme: _simply include a file of the same name in the child theme directory, and it will override the equivalent file in the parent theme directory when your site loads_. with the exception: > Unlike style.css, the `functions.php` of a child theme does not override its counterpart from the parent. Instead, it is loaded in addition to the parent’s > `functions.php`. (Specifically, it is loaded right before the parent’s file.) Source in your case, just copy `single.php` to your child theme and do your edits.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 9, "tags": "child theme, single" }
Buddypress activity id I am working on buddypress activity loop. I want to get current activity id or all activity parameters in entry.php file. but i am not able to get activity id. I am trying to use > bp_activity_id(); But not able to get id. Please help. Thanks
That function is called right in `entry.php` as follows: <li class="<?php bp_activity_css_class(); ?>" id="activity-<?php bp_activity_id(); ?>"> Note that `bp_activity_id()` will echo the value. To use the value in code, call `bp_get_activity_id()`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, buddypress, id" }
How to get image URL from media_sideload_image? I upload external images for media library using following way. $new_image_url = media_sideload_image($new_url, $post_ID, $title); This method return complete img src tag or 'src' for the image URL. I need to get image URL from it?
Try the _fourth_ input parameter (available in 4.2+): @param string $return Optional. Accepts 'html' (image tag html) or 'src' (URL). Default 'html'. So change your code snippet to: $new_image_url = media_sideload_image($new_url, $post_ID, $title, $src = 'src' ); to get the `src` instead of the default `html`. Note that the output might also be an `WP_Error` object for errors, so you might add a check for that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, urls, attachments" }
Filter by custom field in custom post type on admin page I've used Advanced Custom Fields to create custom fields for Competition name, answers etc. I've made a custom post type for competitions as shown on the image and I used Wordpress functions.php to create the columns from my custom fields values. I'm trying to get a "Filter by"-dropdown box with the competitions different names/labels like shown below, but I can only find solutions using taxonomies, which I rather not use **if possible** because I've only used custom fields for everything else. Is it possible to make a custom "Filter by" dropdown using only custom fields? ![Wordpress filter by](
And for displaying result for Filter then try this code add_filter( 'parse_query', 'prefix_parse_filter' ); function prefix_parse_filter($query) { global $pagenow; $current_page = isset( $_GET['post_type'] ) ? $_GET['post_type'] : ''; if ( is_admin() && 'competition' == $current_page && 'edit.php' == $pagenow && isset( $_GET['competition-name'] ) && $_GET['competition-name'] != '' ) { $competition_name = $_GET['competition-name']; $query->query_vars['meta_key'] = 'competition_name'; $query->query_vars['meta_value'] = $competition_name; $query->query_vars['meta_compare'] = '='; } } Change the meta key and meta value as required. I have taken "competition name as meta_key and "competition-name" as select drop down name.
stackexchange-wordpress
{ "answer_score": 14, "question_score": 13, "tags": "custom post types, filters, admin, advanced custom fields" }
Restricting text field to numbers only in Gravity Forms We're trying to restrict a text field to numbers only. Here's what we've tried * Add text field * Apply input mask (9999999999) The problem is that if someone does not fully complete the field, the number is erased when they tab into the next field or if they click anywhere outside of that field. It should not matter how many characters they put into the field, it should just restrict the field to a number. If one only puts one 9 in the field, it restricts the field to 1 number. With the input mask set to ten 9's, you can enter 10 numbers. The problem is that if you do not enter the exact number, it clear the field once it loses focus. We can do this with jQuery but we're hoping that Gravity has a hidden gem we've missed somewhere? ![enter image description here](
If you add a question mark before your string of 9s, this will work as desired. It makes the completion optional. It will still enforce a max limit based on the number of 9s you have but there will be no minimum limit. ![](
stackexchange-wordpress
{ "answer_score": 3, "question_score": -2, "tags": "plugin gravity forms" }
What WP-API authentication method should I use to interact with anonymous / not-logged visitors? I am going to track number of plays of a video in my site by both visitors and users. Whenever the video starts playing I am using JavaScript for the event handling in the frontend and write to `wp_options` or `wp_usermeta` to track these interactions. I was going to make an AJAX request to the `wp_ajax_$action` and `wp_ajax_nonpriv_$action` hooks but I'd like to use this small task as an opportunity to experiment with the new REST API since I heard it is going to replace the old `wp-admin/admin-ajax.php` way of doing it on the long run. How should I approach this?
In WP REST API v2 use the permission_callback found in the Adding Custom Endpoints Docs. <?php add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v2', '/author/(?P<id>\d+)', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', 'args' => array( 'id' => array( 'validate_callback' => 'is_numeric' ), ), 'permission_callback' => function (WP_REST_Request $request) { if ( current_user_can( 'edit_others_posts' ) ) { return true; } else { return false; } } ) ); } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "ajax, authentication, wp api" }
Custom menu output If the menu is with Pages then how can I display the menu item links like this: < I want to use the menu with Angular routes. I believe this can be done with a custom Walker.
You can try the following to modify the links of the menu items that are _pages_ : add_filter( 'nav_menu_link_attributes', function( $atts, $item, $args, $depth ) { if( isset( $item->object ) && 'page' === $item->object && isset( $args->theme_location ) && 'primary' === $args->theme_location ) $atts['href'] = home_url( sprintf( '/#/page/%d', $item->object_id ) ); return $atts; }, 10, 4 ); where we target the _primary_ theme location. This should give this kind of links:
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "menus" }
WP Query crashes on more than ~ 2000 posts Hello there for a custom post type "organizations" I have about 5000 posts which have to be shown in a list with link within one page. However WP_Query just crashes (without PHP timeout just after 4 seconds on the server). Is this a WordPress problem? If so, why do they limit it? Or is it definitly a server problem? $q = new WP_Query(array('post_type' => 'organization','posts_per_page' => 9999));
Querying this many posts is dangerous and you can ( and do ) take the site down. If you absolutely have to do this, you need to adjust your query to be more performant. If you're just needing the link then add `'fields' => 'ids'` to your params - this will only return the post ID and not the whole Post object. You can then use the ID to get the permalink, title etc. If you're not going to paginate, then use `'no_found_rows' => true` this will stop WordPress from running expensive SQL CALC queries to get the total number of posts that the query retrieves. You should 100% cache the results of this query using the Transient API this will allow you to return cached HTML instead of rebuilding this query every time someone hits the page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query" }
WordPress takes too long to show 404 error on images (on LEMP stack) I have installed WordPress on LEMP stack on DigitalOcean and noticed that all the 404 images on the pages are taking too long to show a 404 error message. Those images are not existing so it will give 404 errors but it just takes too long (4 to 6 seconds) to show a 404 error message. ![enter image description here]( Any suggestions?
While it is impossible to pinpoint why it takes so long without access to your server, the core issue is that when the webserver do not find a file it will execute wordpress to handle the URL, and as the URL is unlikely to match any content it will result in a generation of a 404 wordpress page which is obviously much slower than returning 404 at server level. Usually it is not a problem as pages generated by wordpress rarely contain images which do not exist, but if this is an actual problem you can adjust you webserver config (.htaccess for apach) to not propagate unresolved image urls to wordpress.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "404 error, get posts, performance, nginx, server load" }
Show post like this image in my newssite I want to know how to query like this photo in my newssite for a category. See this image and help by give the query code. ![enter image description here]( Do I use Offset or if else. How to query for this .
I'm not sure what you're asking for. If you need a simple query for a category. try generatewp.com for the fastest solution. Here's how to code it yourself. < you'll want to use the **Category_Parameters**
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "php, wp query, query" }
Publishing html directly from ftp to wordpress I have a program for a booking programme and within that is an "Update Website" button which originally would ftp the html created straight in place of the old one meaning once you click update website it will post the most up to date information without having to publish. Only recently changed to wordpress and ma trying to achieve the same thing. I can successfully post into FTP and all, the only issue occurs as I am unsure how to make the link from one page send through to the ftp folder with the html file and therefore view this information without having to login to wordpress and publish it. Any and all help greatly appreciated.
So long as the software publishes everything to a directory, maybe something like: booking/index.html booking/otherstuff.jpg ...then you can just link to it from your WordPress part like you would normally: ...when someone clicks the link, they see the booking section. WordPress is none the wiser, and will happily carry on powering everything else.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, html, ftp" }
How to get all logged in user id in buddypress I want to get all buddypress logged in user's ID. for that sake i am using $bp->loggedin_user->id But this is not helping.. Please help me to get all logged in user id. Thanks.
This `$bp->loggedin_user->id` will only give you a single id, of the _current_ logged in user. btw - it also requires use of the `$bp global`. You don't need to use that global. Use `bp_loggedin_user_id()` instead. BuddyPress does not track logged in users. It does not use sessions. It does use timestamps in the database to indicate recent activity. So you could use custom sql to return user ids. For example: function shahid_get_recent_active() { global $wpdb; $time = time() - (60 * 10); // current time minus 10 minutes $cutoff = date('Y-m-d h:i:s', $time); $user_ids = $wpdb->get_col( "SELECT user_id FROM {$wpdb->prefix}bp_activity WHERE type = 'last_activity' AND date_recorded > '$cutoff' " ); var_dump( $user_ids ); } add_action( 'bp_ready', 'shahid_get_recent_active' ); `$user_ids` will be an array.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "buddypress, users" }
Theme options WP Editor My text editor in Theme Options doesn't have font color option. How can I add that? I've searched around the web, but no luck. On regular pages and posts I can see the font color option. I'm using Options framework. Here's the code snippet: $options[] = array( 'name' => __('Main text block', 'options_check'), 'id' => 'main_text_editor', 'type' => 'editor', 'settings' => $wp_editor_settings );
In theme options, I had to define wp_editor_settings. So, just in options.php, I used: //WP_editor settigs $wp_editor_settings = array( 'wpautop' => true, // Default 'textarea_rows' => 15, 'tinymce' => array( 'plugins' => 'fullscreen,wordpress,wplink, textcolor' )); Basically, I'm adding tinymce plugin.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "functions, theme options, options, wp editor" }
Translating a word with locotranslate, but wordpress does display another by default I use wpadverts plugin and Loco translate to translate the plugin. I'm trying to translate from English to French the "Email" word to "Email" :D. When I translate the word in LocoTranslate plugin, it look fine, and when i try to display it in frontend all my other words are well displayed but the only once who is not well displayed is Email. Wordpress display me "Adresse de contact" instead of "Email". Here is a screenshot from frontend with a print_r(): ![enter image description here]( So, we can see that my label has been translated and called but replaced (maybe) by wordpress core. But if I make a main search in my wordpress folders, I can't find where is these coming from. Did someone had the same issue or any Idea from where is this coming from? Thank you :D Dan
Problem resolved. Wordpress default translation were overriding my translation string. In locotranslate plugin go to settings and click on : Activate the main translation from wordpress. And than you can find and edit your specific string who is overrided.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "translation" }
Broken template went invisible I made my wordpress run local and copied a new template into the templates folder. After logging in to the backend i got the message that the **active theme** (the new one) **is broken** and its reverting to default. So far so good, it reverted to the default theme... BUT the broken one doesn't even show up in the theme selection anymore! How can i check what is broken or missing?... or at least make it visible again. _(I alredy made shure that the index.php exists and i compiled the scss)_
To be a WordPress Theme index.php and style.css are the basic requirement. check Template Folder ( Whatever you name it ) and check index.php and style.css in style.css you can see theme name and other details. WordPress Theme Codex
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, themes" }
How to customize a permalink (URL) structure? i am using $post->guid to get the URL of an attached file to my post. the output is something like this: < [where foo is the file name]. now i want to make a URL like < how can i code that?
The GUID field is _not_ a URL and should never be used for that purpose. It's a unique identifier that happens to look like a URL, but it should never be trusted as such. WordPress has a number of functions for retreiving attachment URLs and files: `get_children` `get_attached_media` `the_attachment_link` `get_attachment_link` `wp_get_attachment_link` `wp_get_attachment_image` `wp_get_attachment_image_src` `wp_get_attachment_url` `wp_get_attachment_thumb_file` `wp_get_attachment_thumb_url` `wp_get_attachment_metadata` The function `wp_get_attachment_image` is probably what you're looking for in this case.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, php, plugin development, functions, customization" }
Wordpress upload path decalration I am trying to use wp-filesystem to write css data.I have things working perfect here. $filepath = get_template_directory() . '/dynamic/'; $wp_filesystem->mkdir($filepath); But this generate files in theme folder. But what is if I want to generate in upload folder? I have tried `$filepath = wp_upload_dir() . '/dynamic/` But it does not work.
Just try $uploads = wp_upload_dir(); $uploads_dir = trailingslashit($uploads['basedir']); $filepath = $uploads_dir . '/dynamic/'; $wp_filesystem->mkdir($filepath); It may help
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, wp filesystem" }
Wp_query Add specific pending posts I want to retrieve in archive all the posts with post_status-> publish and those with post_status->pending of specific user. That's where i'm now: $custom_query_args = array( array( 'post_status' =>'pending', 'author' => 2), array( 'post_status' =>'publish', 'author' => 'any'), 'relation' => 'OR' , 'paged' => get_query_var( 'paged' ) ); $custom_query = new WP_Query( $custom_query_args ); Any help?
Your setup isn't supported by `WP_Query`. One approach is to use the `posts_where` filter of `WP_Query` ( _there are other ways possible, like collecting post ID's instead from different queries._ ) to adjust the SQL query. To avoid string replaces we could use for example: $custom_query_args = [ 'post_type' => 'post', 'post_status' => 'publish', ]; // Add filter add_filter( 'posts_where', 'wpse_where' ); // Query $custom_query = new WP_Query( $custom_query_args ); // Remove filter remove_filter( 'posts_where', 'wpse_where' ); where our custom filter callback is: function wpse_where( $where ) { global $wpdb; return $where . " OR ( {wpdb->posts}.post_author = 2 AND {wpdb->posts}.post_status = 'publish' AND {wpdb->posts}.post_type = 'post' ) "; } Hopefully you can adjust this to your needs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, post status" }
How to decrease picture size On my website, how can I decrease the size of the picture with the cyclists? Currently, I think it's too big.
you will need to add this css to a child theme or install a custom css plugin .blackwell_top_image { height:400px; //change this to whatever height you want the image to be overflow:hidden; } It has to be done this way as the image width is set to 100% so setting a height on the image itself would distort the image. So we are adding the css to the parent container and hiding the rest of the image.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "css, images" }
Wordpress Rest API I'm trying to call a post from a Wordpress install using WP REST API. I keep getting an error in return and I can't find out why. Do I need to authenticate? One website said I don't need to authenticate for a GET request. WP REST API: Version 2.0-beta9. Here is the code I am using: $(document).ready(function () { setTimeout(GetPosts, 2000); function GetPosts() { $.ajax({ url: ' data: { filter: { 'posts_per_page': 1 } }, dataType: 'json', type: 'GET', success: function(data) { console.log(data); }, error: function() { console.log('error'); } }); } })
What version of the REST API are you using? If you're using the version that's bundled with WordPress 4.4 (ie, v2), you'll need to change your `url` to something like ` ## Reference WP API version 2 docs
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "javascript, api, wp api" }
Where does bbPress store author info for anonymous users? I have WordPress and bbPress installed. All is working fine, except that when I need to do a custom query, I don't know which fields in the database to reference for topics created by _anonymous_ users. Usually, using `wp_insert_post`, we would use something like `post_author` and use the ID of the person creating the post, but without the ID, we cannot do much. Any pointers?
I found the answer. Basically it stores them as meta data to the post (added using `wp_update_meta`). It stores them as: _bbp_anonymous_name _bbp_anonymous_email _bbp_anonymous_website _bbp_last_active_time
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "bbpress" }
The acction hook stop working if i move it from plugin file to theme's functions.php file A **bp_includes** is buddypress action and hooked on **plugins_loaded** function remove_bp_docs() { global $wpdb; $current_user = get_current_user_id(); //We are selecting member type before buddypress load so bp_get_member_type won't work neither wp_get_object_terms $query = "SELECT t.slug FROM {$wpdb->terms} AS t INNER JOIN {$wpdb->term_taxonomy} AS tt ON tt.term_id = t.term_id INNER JOIN {$wpdb->term_relationships} AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'bp_member_type' AND tr.object_id = $current_user"; $member_type = $wpdb->get_var( $query ); if ( ! empty($member_type ) && 'client' == $member_type ) { remove_action( 'bp_include', 'bp_docs_init' ); } } add_action( 'bp_include', 'remove_bp_docs', 9 );
Think about what you've written: > The acction hook stop working if i move it from plugin file to theme's functions.php file And: > `bp_includes` is buddypress action and hooked on `plugins_loaded` The problem is that the code stops working when you move the code to `functions.php`, which is a **_theme_** file. The theme loads after plugins load and hence after `plugins_loaded`. Take a look at the hook sequence for a typical page load: < In fact, the first hook available to a theme is `after_setup_theme`. It sounds like your code has to be in a plugin or mu-plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "hooks, actions, buddypress" }
site get login attempts after htaccess ip restriction I'm using a security plugin that keep sending me emails: "A lockdown event has occurred due to too many failed login attempts or invalid username: Username: Admin IP Address: 195.154.243.31 IP Range: 195.154.243.* Log into your site's WordPress administration panel to see the duration of the lockout or to unlock the user." I tried to block the access to wp-admin folder and create htaccess file with this code: order deny,allow deny from all allow from <my ip> also in the root htaccess i added : <Files ~ "(wp-login.php|wp-signup.php)"> Order Deny,Allow Deny from all Allow from <my ip> </Files> how does the attacker/bot try to login?
as @birgire suggest I added `add_filter('xmlrpc_enabled', '__return_false');` to wp-config.php and no attacker/bot tries to login anymore
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "security" }
Dynamic archive of posts by date I'm currently working on an intranet site for a big company and based on the project description, there will be a lot of articles posted everyday so this website will need various archive pages with different queries for users to quickly find articles based on their chosen criteria. I sorted out all of them (thanks to StackExchange!!) but I can't figure out how to create something like below: ![enter image description here]( I want a set number of lines (10 on each sides) each containing the date where posts were published ordered by date. I know how to query posts by date, but to use that it will mean that I will need to update this list everyday manually which is impractical. Is there a way to dynamically create this list (relative to "today's" date)? Thank you in advance for your time on this!
Please note that I have now resolved this issue. For whomever is interested, please find my code below (I've included everything to a shortcode to facilitate adding it anywhere I want): function archiveday() { $x=1; do { $result = date('l jS F Y',strtotime("-$x days")); $year= date('Y',strtotime("-$x days")); $month= date('n',strtotime("-$x days")); $day= date('j',strtotime("-$x days")); $my_query2 = get_posts("post_status=publish&post_type=post&year=$year&monthnum=$month&day=$day"); if ($my_query2){ echo '<a href=" ('. count($my_query2).') <br>'; } else { echo $result .' ('. count($my_query2).') <br>';} $x++;} while ($x<=10); wp_reset_postdata(); } add_shortcode('archive', 'archiveday'); This now outputs the below: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, query posts, list" }
Populating dropdown menu with hierarchical taxonomies Im currently populating my `<select>` elements (I've got plenty of them) with nested `foreach` loops, `get_terms()` and `&nbsp;&nbsp;&nbsp;&nbsp;` to create padding for each nested child element. Each `<select>` code is about 50 lines long and is looking very dirty - I always have to take few minutes to understand what's going on before changing anything. Also, if taxonomy is selected, it includes padding to selected element (if dropdown is closed) which would require unnessesary jQuery to remove padding from selected element. **Is there a WordPress function I could use to populate my dropdowns with hierarchical taxonomies? ( maximum depth is 3 )**
Sounds like you want `wp_dropdown_categories()` to me: $tax_args = array( 'taxonomy' => 'location', 'orderby' => 'name', 'show_count' => 1, 'hierarchical' => 1, ); wp_dropdown_categories($tax_args);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom taxonomy, hierarchical, select" }
How to check custom fields from functions.php I'm trying to hide certain menu items based on the custom fields on a page. I could use CSS or a script to hide the items, that's not the problem. What I don't know is how I can check the custom fields (if field empty then hide item) in my functions.php. Any ideas?
I don't know if you need to hide the element completely, as in "never display it", or if you need to hide it conditionally with JavaScript-- say, to get a toggle effect. Either case is similar and would use `get_post_meta()`. To conditionally display the data use something like: $m = get_post_meta(get_the_ID(),'my_meta_key'); if(!empty($m)) { echo '<div>your data</div>'; } If you want something that you can toggle with JavaScript use: $m = get_post_meta(get_the_ID(),'my_meta_key'); $str = '<div %s>your data</div>'; if(!empty($m)) { $str = sprintf($str,'class="'.$m.'"'); } echo $str;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, menus" }
Taxonomies within plugin invalid I have two taxonomies being registered in a functions file. They are then initialized like so: function foo_register_post_types_and_taxonomies() { foo_register_post_types(); // defined in lib/post_types.php foo_register_taxonomies(); // defined in lib/taxonomies.php } add_action('init', 'foo_register_post_types_and_taxonomies'); The problem is that within a plugin i'm building, those two taxonomies are invalid. I think from what I've been reading is that the plugin runs before the taxonomies have been initialized? How do solve this so I can access these tax's from within my plugin? In other words, outside of the plugin in any template file, when I run **get_terms('school')** , I get an array of terms for the taxonomy 'school'. Running this same code within a plugin returns invalid taxonomy. That's my problem in a nutshell.
Your taxonomies register where you've told them to register, on the `init` hook which is the recommended hook for registering them. That much you are doing correctly. And yes, the plugins themselves will load prior to that hook's execution. You can see that by comparing the `init` hook's location in the load sequence to the `plugins_loaded` hook's placement. You don't say exactly what you are trying to accomplish but the trick is that any code intended to access your taxonomies needs to run on the `init` hook (possibly with a higher than normal priority) or on a later hook.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, custom taxonomy" }
Show One Level Category id This is my cat directory structure * Games * Cricket \-- Bat \-- Ball \-- Wicket * Machines * Electrical \-- Fan \-- generator \-- Computer I am on category page of Bat or Ball or Wicket. Can anyone tell me how i can get its parent id like id of cricket not Games. I want to get the category id of Cricket.
The function `get_ancestors()` will give you an array containing all of the parents of your category with the nearest ancestor being first in the array. So: $cid = 5; // your category ID $c = get_ancestors($cid,'category'); var_dump($c); // debugging $p = array_shift($c); // var_dump($p); // debugging Use `$p` to do whatever you need to do.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Display Search Results after search 1st link As we know that when we search wordpress based site it shows this type URL on browser __ now at this moment our query is **wordpress** for demo please view below link < its first result is my requirement is when user search a query wordpress automatic show 1st result post Instead of result page.
Redirecting to the first result of a search is a very unfriendly thing to do to your visitors and can quite possibly prevent them from ever finding the content they need, but it is very easy to do: function redir_first_wpse_49208() { if (is_search()) { global $wp_query; if (!empty($wp_query->posts)) { wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); exit; } } } add_action('template_redirect', 'redir_first_wpse_49208');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "search" }
CSS only loads in backend This works to load CSS in the backend. I'm trying to load the CSS in both the backend and the frontend though. What am I doing wrong here? function load_top_bar_style() { wp_register_style( 'custom_top_bar_css', plugins_url( 'styles.css', __FILE__ ), false, '1.0.0' ); wp_enqueue_style( 'custom_top_bar_css' ); } add_action( 'admin_enqueue_scripts', 'load_top_bar_style' ); add_action( 'wp_enqueue_script', 'load_top_bar_style');
The _action_ for adding scripts and styles is `wp_enqueue_scripts`, `scripts` is plural. The _function_ for adding a script is `wp_enqueue_script`, `script` is singular. add_action( 'wp_enqueue_scripts', 'load_top_bar_style' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp enqueue style" }
How do I remove or disable "Or link to existing content" in "insert link" dialogue? Don't ask why. Image below pretty much ask what I'm looking to achieve: !screenshot
We could hook into the `after_wp_tiny_mce` with some CSS to hide it, if the `wplink` editor plugin is loaded. **Example:** add_action( 'after_wp_tiny_mce', function( $settings ) { // Check for the 'wplink' editor plugin if( isset( $settings['content']['plugins'] ) && false !== strpos( $settings['content']['plugins'], 'wplink' ) ) echo '<style> #link-selector > .howto, #link-selector > #search-panel { display:none; } </style>'; } );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "links, editor" }
Also show terms that are related to draft and pending posts Im using `wp_dropdown_categories` to output terms in dropdown menu but it only shows terms that are related to **published** posts. I wonder if there's a way / hack to include terms that are related to **pending** and **draft** posts? * * * Codex doesn't say anything about that, also searching the web didn't give any results.
I think you are meaning terms and not taxonomies. For clarity on which is which, see my answer here In general, terms without published posts are considered empty and are hidden in functions like `wp_dropdown_categories()`.Setting `hide_empty` to `0` ( _`false`_ ) in your arguments will display all terms, even the "empty" ones.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, post status" }
Find the page template of the previous page I am am working on a listing type theme and have a search results page that take people to a more details page. I also have links throughout the site that will also take visitors straight to the more details page. On the more details page I would like to display a 'Back to search results' link but only if the user came from the search results page. The only way I can think to do this is to get the page template of the previous page search-results.php and use that as the criteria for displaying the link. Is there a way to get the page template of the previous page, or any other way to achieve this?
You can use `wp_get_referer();` to get a URL of previous page from where user came. Then get the last slug part of the URL. Then compare if the slug matches with slug of your custom search-result page template. Then you can decide whether to show or not to show 'Back to search results' link. Please try below code and feel free to update as intended: <?php $ref_url = wp_get_referer(); $results = explode('/', trim($ref_url,'/')); if(count($results) > 0){ //get the last record $last_word = $results[count($results) - 1]; } if ( $last_word == "about" ) echo "<a href='$ref_url'>Back to search results</a>"; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "page template" }
Delete post meta conditionally after save post I want to update/delete a post meta when a custom post (in this case custom post type is "booking") is updated upon the change of post meta . In my case if user change the post meta `booking_status` to 'denied' and then update the post, then I want to delete the post_meta `booking_status` immediately . Here is what I have tried add_action( 'save_post', 'booking_status_is_updated' ); function booking_status_is_updated(){ global $post; if($post->post_type =='booking'){ if(get_post_meta($post->ID,'booking_status',true)=='denied'){ delete_post_meta($post->ID,'booking_slot'); } } } But this is not working ? How can I get it done ?
* Well, first use the hook properly. The post ID will be passed in. You don't need `$post->ID`. * Second, use the correct hook. If you want to run `save_post` only for your booking type, use `save_post_booking` But otherwise, the code works. I just ran a quick test. function booking_status_is_updated($post_id){ if(get_post_meta($post_id,'booking_status',true)=='denied'){ delete_post_meta($post_id,'booking_slot'); } } add_action('save_post_booking','booking_status_is_updated');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "post meta, save post" }
Disable loading Thumbnail On Mobile I am looking for a script or plugin that disable loading thumb in mobile browser but load thumb on desktop browser. Clearly, in a wordpress website, if I visit a website in desktop browser then website homepage post will load thumb and if I visit this site in mobile browser then website homepage post will not load thumb. How can I stop loading thumb in mobile? Thanks in advanced. Sorry for bad English.
<?php /* if its not mobile */ if ( !wp_is_mobile() ) { /* load and show the post thumbnail */ the_post_thumbnail(); } ?> You can read on wp_is_mobile here and on the the_post_thumbnail here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post thumbnails, mobile" }
Get post meta inline edit WordPress I've noticed that `/wp-admin/js/inline-edit-post.js` is used to retrieved the state of input in quick edit mode. For example the following code : jQuery(function() { if ( typeof mpIds !== 'undefined' ) { jQuery.each( mpIds, function(index, id) { jQuery("tr#edit-" + id + " .my_class" ).prop({checked: true}); console.log( id ); } ); } }); Cannot make this work. But when I enter my code in console it does the job so I'm a little bit lost. How would you do to get the same behaviour for a custom input ?
Not sure it's the best code but I've tested something here that works : (function ($) { // copy of the WP inline edit post var wp_inline_edit = inlineEditPost.edit; // override inlineEditPost.edit = function (id) { // WP edit function wp_inline_edit.apply(this, arguments); // get post ID var post_id = 0; if (typeof( id ) === 'object') { post_id = parseInt(this.getId(id)); } if (post_id > 0 && typeof mp_data !== 'undefined' && $.inArray( post_id, mp_data.ids ) > -1 ) { var edit_row = $('#edit-' + post_id); edit_row.find('.my_class').prop('checked', true); } } })(jQuery); It seems you have to do it this way.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "quick edit" }
Change setting name in Customizer and keep the data I created a theme while back when I was new to Customizer API and for some weird reasons I named theme settings as: `$wp_customize->add_setting('thefunk_theme_options[header_color]` Instead of just `header_color` and saved every setting in an array like `thefunk_theme_options[header_color]` So I recently found out that it's generating some issues, so I want to save every setting, let's say, `thefunk_theme_options[header_color]` to `header_color` or `thefunk_header_color`. Now I know how I can change the settings in the Customizer. However, it will affect everyone who is currently using the theme. All the customization will be gone, so does any one know how I can import the data from the old tables and add it to the new tables?
Personally I think keeping your mods in an array is a nice solution, but transferring them shouldn't be too difficult. Just loop through the array like this: $all_mods = get_theme_mod('thefunk_theme_options'); // retrieve array foreach ($all_mods as $key -> $value) { if (!empty($value)) set_theme_mod ($key,$value); // set array element as separate mod } Since you have to do this only once, when the updated theme is ran first, you may want to insert an extra check upfront and delete the array afterwards.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "theme development, database, theme options, theme customizer" }
Page naming when there is a sub-category only sometimes. I need help with understanding page naming to display a sub-category which only occurs only sometimes. I also need to understand if I need to create a custom Taxonomy to achieve this? I am using CPT UI plugin. I have a CPT, called APPLES. All of my main apple parent types are displaying as images on archive-apple.php. (maybe this should be page?). I will then click on the image of the parent apple type I want to know more about and I will see a sub-page of images/information about that specific kind of Apple. BUT, Sometimes that individual Apple parent will have two or three variations of the main parent Apple. So an intermediary page with two sub-type images must display giving me the choice of what sub-type I want to see. Here is a diagram to explain what I am trying to do. Please and thank you for any help. ![enter image description here](
What do u mean by: > Page naming ?? If you are after a way to implement this situation, then here you go: You have 2 options: **1st Option** Use 'hierarchical' => false while registering your `apples` post type, using `register_post_type`. Then, you will have the option to put apples posts, as parents and children, using the post edit page. **2nd Option** : Use function add_apples_cat_taxonomy(){ register_taxonomy( 'apples_category', 'apples', array( 'label' => __( 'Apples category' ), 'rewrite' => array( 'slug' => 'apples_cat' ), 'hierarchical' => true ) ); } add_action( 'init', 'add_apples_cat_taxonomy' ); to add an `post_type` dependent taxonomy named `apples_category`, and use it to expand the desired hirearchy.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, categories" }
How prevent someone from opening my theme directory How to prevent users from opening my themes directory or at least preventing wordpress from outputting an error. For example when I open this link in my wordpress blog ` I have this error `Fatal error: Call to undefined function get_header() in ..` How can I prevent this from happening ?
You just want to add a check to see if a constant has been defined. If it hasn't you'll know the file is being accessed directly. if ( ! defined ( 'ABSPATH') ) die ( 'No soup for you!' ); Add this to every file you don't want to be directly accessed. Also, anything you add (like this) will be erased when a theme is updated -- unless you built your own theme and have control over that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "themes, directory" }
Using page-something.php as static front page I have created 2 pages inside wordpress "blog" and "hpage", on the config I have set static front page to "hpage" as initial page and "blog" for posts index. Now I want to create a "page-hpage.php" file to create a really especific front page. Looking for the template hierarchy I see that I can use "page-$slug.php", but "page-hpage.php" just doesn't work but if I use "page-$id.php" using the id of the "hpage" I work. Now, If I install this template again the page is likely to not have the same ID again, so it will fail. What I'm doing wrong?
Use 'front-page.php' for your template. You can read more about it at < Or create a page template that you set in the editor. This will allow you to set it on any page and you're not tied to the ID. < <?php /* Template Name: Example Template */ ?> ![Page Template](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, templates" }
Add class to input form in login form is any way to add custom class name to input field in login from in `wp_login_form` function? <input type="text" name="log" id="' . esc_attr( $args['id_username'] ) . '" class="input" value="' . esc_attr( $args['value_username'] ) . '" size="20" tabindex="10" />
While there is no direct filter available to modify the output of username input field. You can do this by enqueuing a js on login page and then adding a css class to username input field. Please see if below helps: add_action( 'login_head', 'add_login_css' ); function add_login_css(){ wp_register_script( 'extra-login-css', get_stylesheet_directory_uri() . '/js/extra-login-css.js', array( 'jquery' ), '', TRUE ); wp_enqueue_script( 'extra-login-css' ); } Make sure the path for **extra-login-css.js** mentioned above is correct or else you can update it as per your directory structure. Add the following code in that js file. ( function( $ ) { $("#user_login").addClass("my-login-username"); } )( jQuery );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "login, wp login form" }
Is there a way to keep a custom menu expanded when editing a custom post type? I am building a plugin that has a custom menu with pages under that menu. A few of those pages are custom post types. I would like to have the main menu stay open when I am on one of those custom post types. Is that possible? Here is what the menu looks like when I'm on a non-custom post type page: ![Open Menu]( But when I click on Makes, Models or Types, the "Squirrels" menu closes because those are managed by the custom post type system. Sorry if this is a duplicate. I looked through some similar questions but didn't see one that had exactly this same issue. Thanks!
I figured this out by putting the main menu slug into the show_in_menu key of the custom post type array like so: $args = array ( 'labels' => $labels, 'hierarchical' => FALSE, 'description' => $title . 's', 'supports' => array( 'title' ), 'show_ui' => TRUE, 'show_in_menu' => 'squirrels_inventory', 'show_in_nav_menus' => TRUE, 'publicly_queryable' => TRUE, 'exclude_from_search' => FALSE, 'has_archive' => TRUE );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "custom post types, admin menu, sub menu" }
Change url-structure for wordpress pages - pages in strucutre not top-level I use wordpress as a cms in which i use a some wordpress pages for standard content and posts for a wordpress blog. Now ive got a problem that the pages should not always be on the top level url and that i can set the url of these pages according to the menu i build. I got a page "service" and inside these navigation-branch there are more pages containing explicit services: Services * Service 1 (url should be: /services/service1) * Service 2 (url should be: /services/service2) * Service 3 (url should be: /services/service3) How can i do that in wordpress? Best solution would be just if wordpress would use the structure from my wordpress menu. Thanks four your help and best regards.
> Best solution would be just if wordpress would use the structure from my wordpress menu. The system doesn't work that way. Menus structure and URL structure are not tied together. You could probably alter permalinks such that this would be the case but it would be a complicated project and potentially cause substantial strain on server resources. The simplest thing to do is to create nested pages via the backend. 1. Create a page called "Services" 2. Then create all of the other pages as children of that "Services" page. The URL structure would by default be like that you describe (assuming that pretty permalinks are enabled and working). Make your menu match.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
plugin_dir_url & plugin_basename not working when plugin dir is outside wordpress dir I have been using these functions for quite a while now but yesterday I noticed that they were not working properly on a site where the plugin directory was outside the main WordPress folder. `WP_PLUGIN_DIR` and `WP_PLUGIN_URL` have been set properly like so: define( 'WP_PLUGIN_DIR', '/var/www/plugins' ); define( 'WP_PLUGIN_URL', ' ); Now if the value of `__FILE__` is `/var/www/plugins/forms-plugin/forms-plugin.php` and I pass it to `plugin_basename()`, I get this: var/www/plugins/forms-plugin/forms-plugin.php Instead of just the plugin name. If I pass it to `plugin_dir_url()`, I get: Instead of the correct value: < Everything works properly when the same plugin is placed inside the WP directory and the constants `WP_PLUGIN_DIR` and `WP_PLUGIN_URL` are not used. Am I doing something wrong? Thanks for your help.
Turns out I was adding a trailing slash to `WP_PLUGIN_DIR` in my `wp-config.php` which was causing this issue. Hopefully this will help someone making the same mistake.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development" }
Forbidden localhost error and error establishing database Hi new to Wordpress development and i'm on a mac. I'm just downloaded MAMP and is using the MAMP Pro trial to run the servers, I've not changed anything, just installed the software and running the servers. I went to < and created a database wpdemo Then i've downloaded Wordpress and dropped it in the MAMP/htdocs folder, I can access the Wordpress installation using < (I can't access the localhost:8888 though, it says 403 Forbidden You don't have permission to access / on this server.) I went through all the steps in the WP installation guide, and after trying to create a database of name wpdemo, i get this message: Error establishing a database connection This either means that the username and password information in your wp-config.php file is incorrect or we can’t contact the database server at localhost. This could mean your host’s database server is down.
Try restarting the services. If you still get the error of Error establishing a database connection, open wp-config.php and check if you have entered the proper database details (username, password, database name, host)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "installation, localhost, local installation" }
wp_list_categories not excluing multiple ids I recently updated to WP 4.4 and im using this code: $args = array( 'orderby' => 'ID', 'show_count' => 1, 'taxonomy' => 'portfolio-type', 'use_desc_for_title' => 1, 'echo' => 0, 'title_li' => '', 'exclude' => '115,161' ); wp_list_categories($args); it's only excluding the first id 115, and ignoring other IDS, any solution for this?
I'm pretty sure this is a Codex error and that the string that `exclude` parameter expects for `wp_list_categories()` is really meant for non-hierarchical tags, such as `blue,red` where hierarchical you _need_ to pass an array of integers: $args = array( 'orderby' => 'ID', 'show_count' => 1, 'taxonomy' => 'portfolio-type', 'use_desc_for_title' => 1, 'echo' => 0, 'title_li' => '', 'exclude' => array( 115, 161 ), ); wp_list_categories( $args ); Always cross reference The Codex with Developer Resources!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, exclude" }
Can admins on network install view and edit users accounts? Is it possible to view the users site and content as admin? Because I was helping someone and I was logged in to the network admin account but when we went to his site url, his dashboard came up and we were able to create new posts and so on. In light of all the privacy violations going on I'd hope I couldn't get into a users account. Or at least have an option to turn that behavior off.
Yes. Yes they can. In my testing and throughout the code you see switch_to_blog(another_blog); do_something(); restore_current_blog(); If you weren't able to do that I think WP would not run.
stackexchange-wordpress
{ "answer_score": -4, "question_score": 0, "tags": "multisite, admin, network admin" }
Deleting images from gallery remain as attachment Process creating a gallery: 1. I create a post with post format _gallery_ 2. I add images from "Add media", note I don't use "Create gallery" but insert pictures into the post 3. update then I have a php side $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) ); this code comes from `gallery_shortcode` function in **media.php**. it works perfect, but when I try to delete image from post, no matter how I try it it is still there. I have not tried this but obviously deleting image permanently from media would work, but I want this images to still remain there. how to delete them as attachments for this images from post editor?
A quick way to detach images is to select Media Library from the menu, Find the images you want to detach, and click the `Detach` link in the `Uploaded to` column. This will remove the value saved in `post_parent` for the attachment.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "media, gallery" }
wp-cli: wp term generate xxxxx - Error: 'xxxxx' is not a registered taxonomy I'm writing a WP CLI command which creates and updates taxonomies using `wp_insert_term`. Actions on my custom taxonomies are not accepted since they don't show up as registered. The wp-cli included Term_Command itself uses `wp_insert_term` and allows actions on default taxonomies but errors on custom taxonomies. Various searches suggest custom taxonomies aren't registered until `init`. Is there a way to run `init` inside wp-cli so custom taxonomies can be manipulated? Anyone got any other ideas?
I figured out a way, although it feels a bit wrong. First test if the taxonomy exists (which it doesn't… the first time at least), and then create it as part of the process… if (! taxonomy_exists($this->taxonomy_manufacturer)) { register_taxonomy($this->taxonomy_manufacturer, 'product'); } if (! term_exists($manufacturer['name'], $this->taxonomy_manufacturer)) { wp_insert_term($manufacturer['name'], $this->taxonomy_manufacturer); } Caveat, register_taxonomy warns of impending doom if it's called outside of `init`. I'm not sure of the implications of it in my scenario, and I'll report back if my spideysense starts tingling, but so far so good.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "wp cli" }
How to show post format gallery metabox image caption in the post front end After getting my images through a metabox for a gallery post format I have the following code to show them on the post front end: <?php if ( !empty( $images ) ) { foreach ( $images as $image ) { echo '<li class="animated fadeIn">', '<figure>', wp_get_attachment_image( $image, 'post-full-width' ), '</figure>', '</li>'; } } ?> I am just wondering now how to show the images captions on the front end along with the images also.
You can add to figcaption on your front-end. <?php if ( !empty( $images ) ) { foreach ( $images as $image ) { $image_post = get_post($image); $caption = $image_post->post_excerpt; echo '<li class="animated fadeIn">', '<figure>', wp_get_attachment_image( $image, 'post-full-width' ), '<figcaption>', $caption, '</figcaption>', '</figure>', '</li>'; } } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "metabox, gallery, post formats, captions" }
Where is the POST response body generated in PHP? I am trying to understand a web app template for wordpress. They do not follow the POST/REDIRECT/GET pattern, and it's very annoying on an HTTPS website. There is a static page with a next button on it. The next button is responsible for pulling the next section and displaying it to the user. After analyzing data, the flow is something like this: 1. Click on "Next" button. 2. POST /section-viewer with two parameters, "next_section_id: 3451" and "hash: 345345" 3. POST responds with page HTML as its body -- which is the full page of the next section, 3451. I have found bits and pieces of the HTML being generated, but I am not able to figure out the final response, and where/how Wordpress/PHP responds to the POST. What I'd like to do is instead of sending the next page's HTML as the body of the POST response, is send redirect, and then redirect the user to the page that has the HTML there.
The answer is, anything that is `echo`d after the POST request, is sent back to the requester via the RESPONSE body. Thus any `echo` statements issued after processing whatever was sent via the $_POST is generated and sent back. In this template's case, it would be better to re-direct the user immediately to a new page, instead of echoing contents back.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "php" }
How to update custom taxonomy meta using ACF update_field() function or any other wordpress function I'm trying to update the Advanced Custom Fields meta value associated with a custom taxonomy term $term_status = wp_update_term( $rate_id, 'rate', $term_data ); $term_id = $term_status['term_taxonomy_id']; update_field( 'field_56829855eebc9',$rate_daily,$term_id ); However, I'm not getting the field updated. I have tried the field name instead of the field key too.
I figured it out somehow.. Syntax of `update_field()`: `update_field($field_key, $value, $post_id)` MY MISTAKE: I was using the wrong parameter for the `$post_id` which i thought was the Term Id of the custom taxonomy term. CORRECT USAGE: rather than using term id (`$term_id` in my question), one should use a string with the taxonomy preppended to the $term_id ie `$post_id` = `$taxonomy.'_'.$term_id` for eg: if your custom taxonomy is `foo` and the term id is `123` then : `$post_id = foo_123` Hope this is helpful for someone. This is the first time I'm asking/answering a question here.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "advanced custom fields" }
Setting category for post as default How can I set a default category from posts that I create? I have tried modify setting options but have not been able to have the default category that I want show up. The current default is "uncategorized"
I just recently did this with a custom post type and custom taxonomy with the following code. function cpt_assign_term($post_id) { $current_post = get_post( $post_id ); // Only apply to new posts. if ( $current_post->post_date == $current_post->post_modified ) { wp_set_object_terms( $post_id, 'default-term_name-or-id', 'category', true ); } } add_action( 'save_post_{your-post-type}', 'cpt_assign_term' ); <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Don't show avatars in media library I am letting users upload avatars which are stored within the uploads folder inside the avatars subfolder which I created. The problem is that avatars are now listed in the media library among other uploaded images. How can I prevent that? I was looking for a filter to filter out what is being displayed but couldn't find one. I wouldn't mind the avatars folder being outside the uploads folder if it has to.
Like most page loads in WordPress, `WP_Query` is intimately involved meaning `pre_get_posts` is your friend. Proof of concept: function step_2($qry) { $qry->set('post__not_in',array(468,303)); } function step_1() { add_action('pre_get_posts','step_2'); } add_action('load-upload.php','step_1'); I'm using the `load-upload.php` hook to isolate the filter to the "Library" page. If you've changed the uploads folder for your avatars you've already got some "upload" code in place. You will need to extend that to track your avatar IDs and retrieve them instead of hard-coding as I did. It might be possible to use some other mechanism to filter the results as well. While I haven't tested this, if you were to upload as some other post type than "attachment" the rest would probably fall into place without further effort.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media, library" }
Buddypress avatar image in database I want to get path of buddy-press profile pic directly in database to be used on other then word-press platform but i am not able to find it in database.. because i can't use buddy-press functions in other platform or language.i am using only buddypress databse. Please help Thanks
BuddyPress does not store the avatar path in the database. It loads avatars using the directory path - usually `.../wp-content/uploads/avatars/`. For example, the full sized avatar for a member might be `.../wp-content/uploads/avatars/1/ef1e70a512662ea4fdca5b2efb6f76ab-bpfull.jpg` where `1` is the user_id. Check your BP installation to find the exact path to the avatars.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, mysql, buddypress, user meta" }
Get product link I want rating from customers by sending mail after order is completed. If customer will click link on mail for review it should redirect to same current product page of my site. How do I do this. I override woocommerce/emails in my child theme. I have customized `customer-completed-order.php` <div class="rating"> <h2> Please Rate this product and review. </h2> <a href=" <img src=" alt="Product Rating"> </a> </div>
WooCommerce default **customer-complete-order.php** email template does not link the order item to corresponding product. You need to use `woocommerce_order_item_name` filter and update the item name to have link. I just tried below code and it adds the link to order item (product name). Put this code in functions.php file of your theme. Hope this helps: add_filter('woocommerce_order_item_name', 'woo_order_item_with_link', 10, 3); function woo_order_item_with_link( $item_name, $item, $bool ) { $url = get_permalink( $item['product_id'] ) ; return '<a href="'. $url .'">'. $item_name .'</a>'; }
stackexchange-wordpress
{ "answer_score": 11, "question_score": 3, "tags": "woocommerce offtopic" }
Use register_taxonomy() in register_activation_hook() I would like to use `register_taxonomy()` to define a hierarchy of geographical terms. It seems that the natural place to place it would be in a function called by `register_activation_hook()` seeing how the taxonomy needs only to be defined once. However, the fine manual explicitly states to "use the init action to call this function". Why? Is the data not stored in the database but rather in memory? If so, might such taxonomies become memory hogs? I cannot anticipate where the end user might use the taxonomies to target anything more precise than init.
> Is the data not stored in the database but rather in memory? Taxonomies (like post types) aren't store in database and needs to be registered on every page load. The build in taxonomies, `category` and `post_tag` are actually registered twice, the second time on the `init` hook. The `init` hook is the earliest to register taxonomies and post types because this is the hook where localization becomes available. This has become the accepted hook to register post types and taxonomies. > If so, might such taxonomies become memory hogs? No. If you are going to register tons of taxonomies (or post types) it might become an issue, but doing that would point to a flaw in your design. Terms on the other hand needs to be be registered once as they are stored in db. Here the `register_activation_hook()` is useful to register terms on plugin activation. Here is an example on how to register terms on plugin activation
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin development, register taxonomy" }
Enqueue script in plugin is not working I can't figure out why this script wont load on site. Am I missing something? function ajax_follow_enqueue_scripts() { wp_register_script('follow', plugins_url('the-follow.js', __FILE__)); wp_enqueue_script('follow'); wp_localize_script( 'the_follow', 'postfollow', array('ajax_url' => admin_url( 'admin-ajax.php' ))); } add_action( 'wp_enqueue_scripts', 'ajax_follow_enqueue_scripts' );
Two reasons your code is not working. 1\. Handle should be same i.e. 'follow' where as you are using the_follow and follow. 2\. You have to execute statements in sequence i.e.(not sure) a) Register Script b) Localize Script c) Enqueue Script Ref: wp_localize_script // Register the script wp_register_script( 'follow', plugins_url('the-follow.js', __FILE__) ); // Localize the script with new data $localize_array = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ); wp_localize_script( 'follow', 'postfollow', $localize_array ); // Enqueued script with localized data. wp_enqueue_script( 'follow' ); * * * **Update 1:** Here is my folder structure ![enter image description here]( and here is the code, its working fine for me ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "ajax, wp enqueue script" }
Publishing Markdown posts from bitbucket to WordPress I have a lot of markdown documents stored in a BitBucket repository. The md documents change often so I use it to track changes. I was now playing with the idea to 'publish' these MarkDown documents to a WordPress site. Is it possible to setup a continuous deployment of MarkDown documents to a WorPress site. And if so, any pointers on how to get this started? Thx,
It is possible although it would take quite a bit of initial setup. I recommend learning about Bitbucket's webhooks. This is how you would have Bitbucket essentially talk to your WordPress install. You would create a plugin or a theme template that has a physical url to it that you point the webhook to. When a commit is made, bitbucket will send a payload to that url and a php script will update the existing post in the database based on the changes made. If it is a new markdown file, a new post is created, if the post already exists, it will update. This would of course be the hardest part of all of it. See wp_update_post & wp_insert_post functions in the WordPress codex:
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "deployment, markdown" }
How to stop wrapping comments in P tag When I update a comment in wordpress, the comment is wrapped with p tag. Here's my code remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' ); remove_filter( 'pre_comment_content', 'wp_filter_kses'); return wp_update_comment( $data ); I removed the `wpautop` filter but the problem didn't disappear. Does anyone know how to solve this problem?
Comments aren't part of the post body. Those won't be effected by the filters that you are trying to use. The core front end comment filters are these: 146 add_filter( 'comment_text', 'wptexturize' ); 147 add_filter( 'comment_text', 'convert_chars' ); 148 add_filter( 'comment_text', 'make_clickable', 9 ); 149 add_filter( 'comment_text', 'force_balance_tags', 25 ); 150 add_filter( 'comment_text', 'convert_smilies', 20 ); 151 add_filter( 'comment_text', 'wpautop', 30 ); You will want to do something like: remove_filter('comment_text','wpautop',30); With `remove_filter()` the priority hook isn't when `remove_filter()` runs, it is the priority of the callback that you are removing. It has to match.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters" }
Get number of root elements in walker class I extended `Walker_Nav_Menu` class as below class YPE_custom_navwalker extends Walker_Nav_Menu{} I want use the `get_number_of_root_elements( $elements )` function that place in to Walker class within my new class `YPE_custom_navwalker` i want use that function for showing the number of root elements within `start_el` function i used this code below but don't work echo $args->walker->get_number_of_root_elements($elements);
I'm not sure if this is what you're after. You can use `$this` to reference the current walker instance. class YPE_custom_navwalker extends Walker_Nav_Menu { public function start_lvl(&$output, $depth=0, $args=array()) { $items = wp_get_nav_menu_items( $args->menu->term_id ); echo $this->get_number_of_root_elements( $items ); parent::start_lvl(&$output, $depth,$args); } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "menus, walker" }
what if one user in WPMU change the theme files? Sorry if my English is not well. In WPMU if one user changes the CSS or other files of theme , what happens to other sites that use this theme ?
> ## Themes > > All themes are installed for the entire network. If you edit the code of one theme, you edit it for all sites using that theme. You can install the plugin WordPress.com Custom CSS to allow each site to tweak their own CSS without affecting anyone else. You can activate themes for the entire network, or edit sites and activate them individually. > > < But "users" don't get to edit themes in Multisite. Only the Super Admin (Network Admin) can do that. > Additional Admin Capabilities > > Only Administrators of single site installations have the following capabilities. In Multisite, only the Super Admin has these abilities: > > * update_core > * update_plugins > * update_themes > * install_plugins > * install_themes > * delete_themes > * delete_plugins > * edit_plugins > * edit_themes > * edit_files > * edit_users > * add_users > * create_users > * delete_users > * unfiltered_html > > > <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite" }
Display File Types For Woocommerce Downloadable Products On Product Page I offer downloadable products with woocommerce and each product is allowed to have multiple files. I would like to display the file types/formats on the product page so users know what each product contains. Please see the image below. ![enter image description here]( One idea I have thought of is to get the names of the attached files, and then somehow print only the last four characters of each one. But I cannot figure out how to write a function that would make it work.
Place the following code in your `meta.php` template file immediately after the lines where it prints the categories and tags. Please note, the standard practice is that you shall copy the `meta.php` template file to your theme folder. So to override `meta.php`, copy: **woocommerce/templates/single-product/meta.php** from plugin folder to **yourtheme/woocommerce/templates/single-product/meta.php** <?php global $product; $downloads = $product->get_files(); foreach( $downloads as $key => $each_download ) { $info = pathinfo($each_download["file"]); $ext = $info['extension']; $formats .= $ext . ", "; } echo '<p> Formats: '. $formats .'</p>'; ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "woocommerce offtopic" }
Conflict with single and double quotes This might be a very silly question but I am losing my hair over this.. So basically, I have the following line of code" 'Default' => '<img src="' . THEMEROOT . '/admin/images/default.png" width="120" height="80" alt="<?php _e( 'Default', 'my_theme' ); ?>"/>', The problem I am having is the alt text is printing like this: <?php _e( 'Default', 'my_theme' ); ?> instead of just the "Default" word.. It is a conflict between double and single quotes, but I can't figure out how to fix it. What am I doing wrong here?(please be gentle, I am a new in these things :))
It's sometimes easier to work with `sprintf()`: 'Default' => sprintf( '<img src="%s/admin/images/default.png" width="120" height="80" alt="%s" />', get_template_directory(), esc_attr__( 'Default', 'my_theme' ) ); where we use the `esc_attr__()` to return a translated value that's safe to be used in an attribute, but I'm not sure what your `THEMEROOT` contains, so I just replaced it with `get_template_directory()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, translation" }
How to determine the template loaded when you are not an Admin? I have a page that displays differently based on what type of user I'm logged in as, and I can't figure out why. Specifically, if I'm logged in as an Admin, the page displays one way, but if I'm logged in as any other type of user that is not an admin, the page displays a different way. I have tried using a plugin called Query Monitor that lets me see what template is being used to display the page, but its information is only visible when I'm logged in as an admin. So I can't see which template file is being loaded if I'm logged in as a non-admin user. Is there some way to determine what template file is being used to display a page when one is not logged in as an admin?
Look at the generated source code (view source in your browser) for the page. Find the `body` tag and look at the classes. If your theme is doing things correctly you should see tags associated with the template. They are pretty obvious but for reference: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "template hierarchy" }
WP plugin calls for custom pages I'm trying to create a custom landing page for my site. I am using wordpress because of the SEO plugins they offer. Mind you I'm not an expert so this might be an obvious question (please be gentle) How would I be able to include a plugin like Yoast to a custom page template? In general, how what is the best way to include plugins into your custom pages? If someone could point me in the right direction or perhaps provide some documentation for me to read, that'd be great. Thanks for the help. [EDIT] I was asked for clarification so hopefully I am able to clarify my question a bit. I want to include my wordpress plugin in a custom landing page I'm hand building (coding myself). To include these plugins, would I do calls somewhere in my custom code for the landing page? What do I necessary have to do? Hopefully this is a little more clear. Thanks guys :)
You don't have to "include" plugins. Plugins operate, or **_should operate_** , by means of the extensive "hook" system built into WordPress core. Once activated, a plugin should not require much else (with a few exceptions for very complicated plugins). What you need to do is make sure that you are using the appropriate Core functions classes to generate content-- such as `get_header()`, `get_footer()`, `the_content()`, `the_title()`, `WP_Query`, `get_template_part()`. It is a very, very long list. This related answer might help: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, customization, templates" }
How to map a URL to a specific template? I have a URL like < that I would like to map to a specific template file. At the moment I am achieving this by enabling permalinks and creating the pages "arbitrary" and "path" (page "arbitrary" is set to parent of "path") then choosing a custom template. The downside to this is that the client could delete these pages thus breaking the site. Anyone know of a better way? Like something I could add to functions.php.
Please place below code in your theme's functions.php file & let me know how it goes :) add_action('wp', function(){ list($uri, $qs) = explode('?', $_SERVER['REQUEST_URI']); if ( $uri == "/arbitrary/path" ) /* Change this to path that you want to match*/ { locate_template( "template-full-width.php" , true, false ); /* Don't forget to replace template name with actual template which you want to load */ die(); /* So that WordPress does not load its template as per template hierarchy. */ } });
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "permalinks" }
Audio post format with Advanced Custom Fields I am using the Advanced Custom Fields plugin to create custom fields for post formats. I have a field that only displays when the audio post format is selected. This is a text filed where the user places a url from a soundcloud audio file, for example and then the the audio file should show on the front end of the post. However, I am having issues making this work. I have done the same process for the video post format and its working properly, however for audio files I am not having any luck so far. The field I have created has the name of audio_post_format_url. And the code bellow gets the value of that field and echoes it: $audio = get_post_meta( $post->ID, 'audio_post_format_url', true ); echo wp_oembed_get( $audio ); But at the moment nothing gets echoed.. what am I doing wrong here?
Advanced Custom Field plugin uses `get_field()` to retrieve values. Your code should be something like: $audio = get_field('audio_post_format_url', $post->ID); var_dump( $audio ); # To make sure you're retrieving the right value echo wp_oembed_get( $audio ); Note that `get_field()` does not need a second parameter, it will take the current post ID if omitted. If `var_dump( $audio )` displays `false`, then you should check your ACF key.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, post formats, audio" }
get woocommerce My account page link I am trying to send an email to customer after purchased products and when customer click on the the link provided the email for rating the product it should redirect to customer's account/My account page. I put some code in functions.php to get the WooCommerce My Account URL: $myaccount_page = get_option( 'woocommerce_myaccount_page_id' ); if ( $myaccount_page ) { $myaccount_page_url = get_permalink( $myaccount_page ); } I have customized into **customer-completed-order.php** and put this code <h2> Go to your account page for review </h2> <a href=" <img src=" alt="Product Rating"> </a> I want to get woocomerce myaccount url in above code. how should i do this.
You can get the WooCommerce my-account URL as below <a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('My Account',''); ?>"><?php _e('My Account',''); ?></a> Now you can insert this in completed order mail template too. <h2> <a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" title="<?php _e('My Account',''); ?>">Go to your account page for review</a> </h2> <a href=" <img src=" alt="Product Rating"> </a>
stackexchange-wordpress
{ "answer_score": 40, "question_score": 24, "tags": "woocommerce offtopic" }
Show post titles within Wordpress bootstrap Dropdown menu I created custom bootstrap navwalker class for my wordpress theme all things work correctly i has this code below within `function start_el(){}` When i put `<h2>Hellow World!</h2>` within `$item_output` the dropdwon menu show the `Hellow World!` four times in four column But when i want put the `the_title()` wordpress function within `$item_output` like this `<h2>'.the_title().'</h2>` Show me the `Hello World!` post title above the main menu items, not within the dropdown menu How i can solve this problem? if (!empty($item->divideto_4)) { $col = 3; $divide_to = 12 / $col; //4 for ($i=0; $i<$divide_to; $i++) { $item_output .= '<div class="col-sm-'.$col.'"><h2>Hellow World!</h2></div>'; } }
Thank you for our reply i solved my problem i used Wordpress loop query for showing last fout posts in four column as below if (!empty($item->divideto_4)) { $col = 3; $divide_to = 12 / $col; //4 $my_query = "showposts = ".$divide_to; $my_query = new WP_Query($my_query); while ($my_query->have_posts()) : $my_query->the_post(); $item_output .= '<div class="col-sm-'.$col.'">'; $item_output .= get_the_title(); $item_output .= '</div>'; endwhile;*/ $YPE_col_content->YPE_lastposts(); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, walker" }