INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Show comments in Backend
On my website I implemented, that every user can comment on every image on the site. So it is possible to comment every image in a blogpost for example. Everything works fine and I can display them on the frontend.
My question is, how can I display them in the backend? I can access them in the database like the comments written in the normal commentform.
I hope I could clearly explain what I want. If not, ask me please. Thanks! | I answered my question coincidentally in the comments section. Just put your self made comments in the right table: wp_comments and everything works like a charm... :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp admin, comments"
} |
Use URL parameter to create dynamic content
I need to get the following task done: My client has a huge product database with way over a thousand different products with tons of details. We don't want to generate every product page individually. The idea was to get the parameters from the url, run a query against the db and display the result on a more or less static page.
I'm pretty new to wordpress and there is most likely already an approach for my problem. Any hints?
Greetings Fabian
. I did an "inspect element" and the checkbox seems to have to do with cookies consent (see second screen capture), but there's nothing written next to it, and I don't know if I can remove it.
Does anyone know anything about this?
 European Union law "The General Data Protection Regulation" (GDPR).
When checkbox is checked, it says the browser to save the name, email and website in the cookie to reuse them later.
When comment form `<label>` is CSS-styled the right way, the label text " _Save my name, email, and website in this browser for the next time I comment._ " it visible. Also you can inspect it in Developer Tools like you've done with `<input>`.
If you are not affected by GDPR, simply remove the checkbox putting the following code in your theme's `functions.php`:
add_filter( 'comment_form_default_fields', 'comment_form_hide_cookies_consent' );
function comment_form_hide_cookies_consent( $fields )
{
unset( $fields['cookies'] );
return $fields;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "updates"
} |
Display Custom Post Category Count & WordPress Category Count Using Shortcode
I am trying to create a shortcode to display the posts count of a custom post type as well as standard post categories. I have successfully done this using this code snippet from a similar post:
// Add Shortcode to show posts count inside a category
function category_post_count( $atts ) {
$atts = shortcode_atts( array(
'category' => null
), $atts );
// get the category by slug.
$term = get_term_by( 'slug', $atts['category'], 'category');
return ( isset( $term->count ) ) ? $term->count : 0;
}
add_shortcode( 'category_post_count', 'category_post_count' );
The code above only works for standard wordpress post categories, not custom post types. Any help is appreciated. | It's because you are have passed " **category** " in " **get_terms_by()** " function as third argument.
Please replace " **add_custom_taxonomy_here** " with your custom taxonomy slug in below code.
// Add Shortcode to show posts count inside a category
function category_post_count( $atts ) {
$atts = shortcode_atts( array(
'category' => null
), $atts );
// get the category by slug.
$term = get_term_by( 'slug', $atts['category'], 'add_custom_taxonomy_here');
return ( isset( $term->count ) ) ? $term->count : 0;
}
add_shortcode( 'category_post_count', 'category_post_count' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, count"
} |
get_post_meta pagination
I have custom field, array with multiple values
$metas = get_post_meta($post->ID, "$meta_key", false);
foreach ( $metas as $metas ){
echo $metas;
}
Of course this will return an array.
How to paginate this? So for example:
www.example.com/post-title/1
will return `meta_value[0]`
and
www.example.com/post-title/2
will return `meta_value[1]`
and so on... | On a singular view, the current page number can be accessed with `get_query_var('page')`. You need to subtract 1 to get the corresponding array value. Note that the first page will redirect to the URL without page number, this is just a thing WordPress does.
// get meta
$metas = get_post_meta( $post->ID, 'your_meta_key', false );
// get page number
$page = get_query_var( 'page' );
$page = $page > 1 ? $page - 1 : 0;
// output meta for this page
if( isset( $metas[$page] ) ){
echo $metas[$page];
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "post meta"
} |
How do I change the style of just a part of the tagline?
I'd like my tagline to have specific styling - but not all of the tagline, but just some words should be bold/italised/different color. How do I wrap `<span>` around specific tagline words? Can it even be done?
I know how to change the style of tagline in general (targeting `.masthead-content p`), but this affects the whole tagline. I need to target specific part of it. Thank you! | A quick search online for html in your tagline came to this site: <
It seems like it is your answer.
It explains that you would update your theme file to use the echo html_entity_decode function:
<h2 class="tagline"><?php echo html_entity_decode(get_bloginfo('description'));?></h2>
Then, you can just use html in your admin > settings page like so:
This is <span class="some-class">my tagline</span> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "css, description"
} |
Wordpress allow access only one custom post type "xyz" to custom user role but need to hide all admin panels
I have Wordpress website and has some user roles and I want to show related admin panels for their roles.
I have checked few user role plugins but not found any solution.
basically, We need to set up a user role "manager", who can only access few menus at backend like custom post type "manager_deals" but need to hide all panels in admin. | You can use a free WordPress plugin **Adminimize** to provide access of custom post type or admin menu to the specific type of user role.
Adminimize: <
Hope this helps...Let me know if you need any additional help. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, users, capabilities"
} |
Where is this inline CSS code
Where is this CSS code?
I mean the `margin-top: 46px !important!;` I need to change it to `1px` to rid of top margin. But i didn't found it in any theme's files.
**Note: I have searched the texts in all files usingFileSeek Pro**. But didn't found anything. (even with Inspect Element in the Firefox)
` and it's called as hook on `wp_head`.
So how to get rid of it? Just remove this action from that hook:
function remove_admin_bar_bump() {
remove_action( 'wp_head', '_admin_bar_bump_cb' );
}
add_action('get_header', 'remove_admin_bar_bump');
Then you can add it in your CSS and use `body.admin-bar` as context if you want to add some styles only if the admin bar is visible. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "filters, css, admin bar"
} |
Add a post metadata if only the key and value does not exist
In a WordPress post, these multiple values exist for a custom metadata with the key "client"
client=>Andy
client=>Johny
client=>April
I want to add a new metadata only if its value does not exist,
Result wanted: client=>Andy will not be added because it already exists.
client=>Susan will be added because it does not exist The post will now have these metadata values
client=>Andy
client=>Johny
client=>April
client=>Susan | OK, so you have some code that uses `add_post_meta` and you want to make it add only unique values.
The problem in here is that `add_post_meta` does exactly what it's name is saying - it adds a post meta value. There is 4th arg for that function that's called `unique`, but it work based on key and not value.
All of that means that you have to do the checking by yourself... So you'll have to get all meta values using `get_post_meta` for that key and check if there already exists a meta with given value...
So how can that look like?
Somewhere in your code is a line looking like this:
add_post_meta( $post_id, $meta_key, $meta_value );
Just change it to this:
$existing_pms = get_post_meta( $post_id, $meta_key );
if ( ! in_array( $meta_value, $existing_pms ) ) {
add_post_meta( $post_id, $meta_key, $meta_value );
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "post meta"
} |
home is not working in wordpreess
all Inner pages are working fine but home page is not working admin is working fine
home page not working I have added wp-confing file
define('WP_DEBUG', true);
define('WP_ALLOW_REPAIR', true);
define( 'WP_DEBUG_DISPLAY', true );
but not get any error
home page dispaly blank I have check all plugin disable but still error are coming | I have to remove "/" in a wp-option table site URL | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes"
} |
Safe to start a php session on get_header action?
I now usually php sessions are started from the init hook, but get_header runs before writing the page, sono technically speaking, I can open a session from there. Is there any other reason I should not do it?
add_action('get_header', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');
function myStartSession(){
if(!session_id()) {
session_start();
}
}
function myEndSession() {
//session_destroy ();
} | There’s nothing that requires that `get_header` run before output starts, you could put it in the middle of a template file after other content and still have a perfectly valid theme.
`template_redirect` is the last action where it is guaranteed that no output has started yet. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "headers, session"
} |
Ajax response returns html code instead of user data
Ok, so I ran into an issue where I had disabled access to the default WP dashboard for specific user roles; however, this also inhibits ajax calls to the ajax-admin.php endpoint, which is necessary for what I am trying to do. If anyone knows a useful workaround for this particular scenario that does not require a complete redesign, I would appreciate it, as I do not really see any information on this particular issue. Thank you in advance! | You could replace your call to wp_ajax for a custom REST endpoint.
This should be useful: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, ajax, dashboard"
} |
How to add a checkbox to registration and user profile?
I need to add a privacy policy checkbox to user registration AND user profile (checkable and uncheckable at anytime in your user life). I was thinking there would be tons of plugins doing this, but I am searching for hours not finding anything suitable.
I could find how to add a checkbox programmatically to registration form (like this) but not on the user profile. So how this can be done? | To add fields on user profile page,there are some filters for displaying them and some filters for saving them and another action for updating personal options. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "user registration, profiles"
} |
Display single category name in woocommerce loop
I want to display woocommerce single item category in shop loop. And i am using hooks action. Here is my code:
<?php
remove_action('woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10);
function loop_title() { ?>
<div class="col-xl-3 col-md-3 col-sm-3">
<h3><a href="<?php the_permalink(); ?>" class="feed-item-baslik"><?php the_title(); ?></a></h3>
<?php
global $post;
$postcat = get_the_category( $term_id );
if ( ! empty( $postcat ) ) {
echo esc_html( $postcat[0]->name );
}
?>
</div>
<?php }
add_action('woocommerce_shop_loop_item_title', 'loop_title', 10);
?>
But it not displays category name. And i also tried get_queried_object and get_term. | <?php remove_action('woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10);
function loop_title() {
global $post;?>
<div class="col-xl-3 col-md-3 col-sm-3">
<h3><a href="<?php the_permalink(); ?>" class="feed-item-baslik"><?php the_title(); ?></a></h3>
<?php
$terms = get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) :
if ( ! empty( $terms ) ) {
echo $terms[0]->name;
}?>
<?php endif;?>
</div>
<?php }
add_action('woocommerce_shop_loop_item_title', 'loop_title', 10); ?>
Replaced **get_the_category()** with **get_the_terms()**. Hope this helps !! | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "categories, loop, woocommerce offtopic"
} |
how to set title of each page or post for SEO
I developed my theme. and I set header.php.
And in Header.php, I set like this.
<title>My Site Name</title>
This makes search-engine confuse. Every page and posts title in head tag are same with site-name.
Do you have tips to set the title and meta tag for SEO? | To properly set the title tag in a theme you shouldn't put it in header.php manually. Your header.php should have `wp_head()` somewhere between `<head></head>`, then you can let WordPress set the title tag by adding support for `title-tag` to your theme:
function wpse_304818_theme_setup() {
add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'wpse_304818_theme_setup' ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "seo"
} |
How to use $wpdb (from the template) to update the DB, without being an admin
In a template file, where some backend PHP code is, how can I use the `$wpdb` to update the DB, without being logged in as admin. Every time I go to the template, I'm constantly being redirected to the login page, if I am not logged in as admin. I want to be able to use the `$wpdb` inside the plugin, to have some DB updates in the PHP code of the template - without being an admin. | It seems like you're trying to use $wpdb without first declaring the global $wpdb. You should not need to enqueue admin.php in order to use $wpdb.
add:
global $wpdb;
to the top of your function instead.
If you're trying to run code in a file without passing it via wordpress (i.e. you're just navigating to /somefile.php) make sure you include wp-load.php (although this is NOT best practice). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "templates, admin, wpdb"
} |
Programatically import custom fields using wp all import
I have a csv with a lot of custom fields that I need to import. It would take too much time to manually set up the fields using the interface and it also is not very client friendly to ask them to make sure the values match up. Many of the values must also be mapped from the csv to a different value in the custom field in WordPress. | WP All Import has a lot of undocumented features in the various hooks, actions and filters implemented in the code. The easiest way to do such a mapping is to add a filter to the `pmxi_options_options` and add custom rules. These rules will show up under the Custom Fields accordion during the import configuration step.
<?php
add_filter( 'pmxi_options_options', function( $options ) {
// Match the desired custom post type
if ( $options['custom_type'] != 'product' ) {
return $options;
}
// Configure the custom fields
$options['custom_name']['custom_field_name'] = '_custom_field_name';
$options['custom_value']['custom_field_name'] = '{csv_column[1]}';
$options['custom_mapping_rules']['custom_field_name'] = json_encode( [
'value_from_csv' => 'value_to_custom_field',
'en' => 'English',
] );
return $options;
} );
`. However, this returns the data I want wrapped in HTML.
I'd like to get the data but not wrapped in HTML.
I presume this means using a function that returns an object, and from that point I'd work with the object. `get_terms` looks like a likely candidate. But I haven't been able to craft the parameters correctly.
How exactly can I get the data I want? | OK, so let's make it straight:
get_the_term_list
> Returns an HTML string of taxonomy terms associated with a post and given taxonomy. Terms are linked to their respective term listing pages.
So it will generate HTML code and return it as string.
get_terms
> Retrieves the terms in a given taxonomy or list of taxonomies.
So it has nothing to do with current post.
get_the_terms
> Retrieve the terms of the taxonomy that are attached to the post.
So this is the one you're looking for, I guess.
It will get the terms of given taxonomy that are assigned to given post and return them as array - so you can iterate it and do whatever you want with them... | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, terms"
} |
How to make "virtual" translation with polylang installed (but without Polylang)
I have a CPT called "domaines" (its like vineyards in french). My site have 2 languages (french and english), configured with Polylang for **pages** and **menus** translation.
I don't want to use Polylang features for my "domaine" CPT translations to avoid duplicating posts : I want to use ACF for translations (with a condition on the current language inside the template) because there is only 3 fields to translate (and I have more than 1000 posts).
I want an URL like : www.domainame.com/ **en** /domaines/my_slug The www.domainame.com/domaines/my_slug already exists (it's my original post in french).
There is a way to create a "virtual" page on "/en/" with the same content as "/" ?
Thank you | I've found a (I think) reliable solution to do that:
add_action('init', 'add_my_rewrite_domaines');
function add_my_rewrite_domaines() {
global $wp_rewrite;
$wp_rewrite->add_rule('en/vineyards/([^/]+)','index.php?post_type=domaine&domaine=$matches[1]','top');
$wp_rewrite->add_rule('en/vineyards','index.php?post_type=domaine','top');
$wp_rewrite->flush_rules();
}
Now I have all my posts, virtually duplicate, without any creation of pages or extra templates.
In Polylang, I've deactivate translations for my 'domain' CPT. Everything works well. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin polylang, routing"
} |
Does WP fire delete_post when trashed posts are automatically deleted?
I have a custom db table that stores additional post data and I need to delete posts from my custom table when the original post is deleted.
Will WP fire the `delete_post` action below and run `my_function` when WP _"automatically"_ deletes posts that have been trashed?
add_action( 'delete_post', 'my_function');
I can set up an option to manually purge my custom table if needed but I would prefer it to happen automatically. | ## Short answer
Yes, it does ;)
## Long answer
The function that is used to empty the trash/remove trashed posts is called `wp_scheduled_delete`. When you'll take a look at it's code, you'll see, that it uses `wp_delete_post` to delete the posts and inside `wp_delete_post` the action `delete_post` is run as you can see here. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "plugin development, hooks, actions, trash"
} |
How to add 2 hours to the wordpress time formed with current_time("mysql", false)?
How to add 2 hours to the wordpress time which has already been formed using `current_time("mysql", false)`? | The WordPress `current_time()` returns the current time in the format specified in the first parameter. In your example code, this is the `mysql` value. The second parameter represents a timezone option. The default returns the local time for the timezone specified on the site's Settings > General page, or GMT depending on the value supplied when calling the function.
<
If time mathematics are still required, using the PHP `strtotime()` function is useful for this:
$now = current_time( 'mysql' );
echo 'It is currently: ' . $now . '<br>';
$later = date( 'Y-m-d H:i:s', strtotime( $now ) + 7200 ); //7200 seconds = 2 hours
echo 'In 2 hours it will be: ' . $later; | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "mysql, date, date time"
} |
Bulk update set of URLs via SQL
I've checked multiple questions and can't seem to find the answer.
How can I update a list of URLs to either include "-google" at the end of the permalink, or set the URL to a custom url. My list of URLs is 100+ and I have what the URL is and what the URL should be.
**For example:**
_change to:_
**I have already updated the URLs in the post_content using this below:**
UPDATE wp_posts SET post_content = REPLACE (post_content,'
That worked for the post content, but it's not a solution to update the permalink of those pages, which is what I need. | OK, so let's assume you have these URLs in some array (if you don't, you can easily prepare it using any developer text editor, I guess). Let's call that array `$slugs` and let's say it's defined like so:
$slugs = array(
'customer-name' => 'google-customer-name',
...
);
So there are only slugs in there.
So now you'll have to modify the posts:
global $wpdb;
foreach ( $slugs as $old => $new ) {
$wpdb->update(
$wpdb->posts,
array( 'post_name' => $new ),
array( 'post_name' => $old )
);
}
This will change the slugs, hence the permalinks, for these posts. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks, sql"
} |
WP_Query that targets all categories
I've done a bit of `wp_query` work before, but always targeting certain categories.
I want to do a `wp_query` that uses all the categories, but it is not displaying anything.
This is my code:
// WP_Query arguments
$args = array(
'nopaging' => false,
'post_type' => 'posts',
'posts_per_page' => '4',
'meta_key' => 'partner',
'meta_value' => $post_id
);
Nothing is coming through yet and if I add a cat and no:
// WP_Query arguments
$args = array(
'nopaging' => false,
'post_type' => 'posts',
'posts_per_page' => '4',
'cat' => '5',
'meta_key' => 'partner',
'meta_value' => $post_id
);
It pulls the posts in.
I've searched in Google, but found nothing hence I am asking. | It's hard to say exactly why adding the category changes anything, but... The query looks OK... Almost... There are some things that concerns me:
1. `'post_type' => 'posts',` \- there is no built-in post type called `posts`. You should use `post` in there, unless it's your CPT (but then... I don't think it's a good name ;))
This is the biggest concern. But there are some minor ones also:
1. `'posts_per_page' => '4',` \- it should be a number, it will be converted, but why should it have to...
2. `'nopaging' => false,` \- it's default value for this arg, so there is no point of setting it. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, wp query"
} |
How to remove padding and margin between divi rows?
I have two divi rows, each row contains 3 columns, each column contains a Blurb module item.
I want to remove padding and margin top and bottom for those 2 rows, I want padding and margin 0px, how to do that? I set it from the design, you could do that in the spacing section but there's still an empty space.
.
;
and then trying to insert the data:
$newdb->insert('tablename', array('fullname'=> $_REQUEST['fullname'],'email'=> $_REQUEST['email']);
but i am not able to insert the data into new table of the new database.
its showing the error "ERROR ESTABLISHING A DATABASE CONNECTION".
Please try to resolve my query | Look at the order of the constructor arguments in the documentation:
> `string $dbuser, string $dbpassword, string $dbname, string $dbhost`
You've got the arguments in the wrong order. Move the host to the end:
$newconnection= new wpdb("username","password","databasename","localhost"); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wpdb"
} |
Woocommerce shows empty columns
In my wordpress site, i installed woocommerce. In archieve categories and shop page the products not setting correctly.
They looks like:
XXX
X
XX
But I want to display correctly in the grid:
XXX
XXX
XXX | Finally, I got the answer. By setting a particular height to the (only height and it don't need width), I got the answer as i Need.
Thankyou | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "woocommerce offtopic, archives"
} |
Get post / page ID from ACF Link field
I'm trying to recieve post ID from link using ACF link field:
<?php
$link = get_sub_field('offer_link');
$id = get_the_ID();
if( $link ): ?>
<a href="#post-<?php echo $id; ?>" target="<?php echo $link['target']; ?>"><?php echo $link['title']; ?></a>
<?php endif; ?>
but instead of ID of link I get the ID of current page. How should it be done? | The Page Link documentation actually shows how to retrieve the ID from a Page Link field. Just needed to do this myself and came across it. It worked well for me.
<?php
// vars
$post_id = get_field('url', false, false);
// check
if( $post_id ): ?>
<a href="<?php echo get_the_permalink($post_id); ?>"><?php echo get_the_title($post_id); ?></a>
<?php endif; ?>
The "false, false" parameters allow you to retrieve more details. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "links, id"
} |
Log IP of users who click a button?
Is it possible to create a new database table to log the IP addresses of users who click a specific button? This is a bit above my PHP/JS skill level so I'm trying to gauge the difficulty of doing this. Thanks so much! | It depends on how the button works.
For instance, you can make an API. When the button is clicked, you can call the api via Ajax and save the IP during the process.
Or most likely you will write ip via action hook, if the button call the hook. In this case, you will use user agent. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "database, ip"
} |
is_shop doesn't work for woocommerce
I want to hide woocommerce breadcrum in only woocommerce archive page. And i want to display it in single product. So i write this code in functions.php:
if(is_shop()) {
remove_action('woocommerce_before_main_content', 'woocommerce_breadcrumb', 20);
}
But it not hiding. | `is_shop()` is returning false because the WordPress query isn't set up yet when `functions.php` is run. If you attach it to a hook, like `wp_loaded`, it should work.
add_action( 'wp_loaded', 'remove_main_content' );
function remove_main_content() {
if( is_shop() ) {
remove_action('woocommerce_before_main_content', 'woocommerce_breadcrumb', 20 );
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Problem forcing San SSL certificate on Wordpress
I couldn't find an answer already to this question, so I'm asking my first ever question on StackExchange.
We recently changed our platform from a GoDaddy managed Wordpress platform, to GoDaddy's Linux platform, and have been managing the gremlins ever since. We paid for migration from the old platform to the new one, and we have been having SSL issues ever since. I'm including a screenshot of the issue for reference. In fresh spin ups of Wordpress, using a San SSL, the issue doesn't exist, but it does exist on the two that were migrated over. We've installed multiple plugins to force the SSL, but a couple of pages still show as being unsecure. The reference URL for a broken page is < , which still shows mixed content.
 you can view the details under the Network panel. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "ssl"
} |
How to Populate the list of custom post type categories
Default categories are populated like this →
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) : // to make it simple I use default categories
echo '<select name="categoryfilter"><option value="all">All</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->slug . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
 );
But if you want to show a select filled with terms of given taxonomy, there’s a function for that:
wp_dropdown_categories( array(
'show_option_all' => 'All',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 1, // change to 0 if empty terms should be shown to
'echo' => 1,
'selected' => 0,
'name' => 'categoryfilter',
'taxonomy' => 'vcategory',
'value_field' => 'slug',
) ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, functions, categories"
} |
Should I use wp-content/cache or [PLUGIN_DIR]/cache?
I've been looking at some WordPress plugins, and I notice that if these plugins cache files, they will store these files in _wp-content/cache/[PLUGIN_NAME]_. Is there any particular reason why they store it there instead of inside their plugin directory?
The way I see it, the latter way allows the cached files to be deleted even if the plugin is deleted through (S)FTP. | When a plugin is updated, its folder gets deleted and recreated with the updated version. This would destroy any caches, which on a heavily trafficked site could bring down the server
Additionally, the plugins folder on a lot of servers is read only to the user the web server runs as for security reasons.
It also improves management. If you want to clear cache, you don't have to empty multiple folders across a site, when you have a single cache folder to clear out.
But keep in mind though, that all these plugins give tiny improvements when compared to the massive boost a dedicated object cache will provide. I **strongly** recommend a Memcached/Redis based setup.
Also, file based caches won't work on a lot of systems, e.g. on a busy cheap/shared host server, it might be faster to generate the page than it is to retrieve it from the disk, with the end result being that your site runs slower not faster | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, cache"
} |
Send Mail with link to current_user
I need a plugin which should send an mail to the "current_user" after a click on a "send" button. The reason for this that I have some pdf.files which should not be downloadable directly. There is a short description of the Pdf with a "send" button. If the user click the button a "download link" should be sent to his login mail.
I have tried a lot of different form-plugins, but none of this accepts a shortcode in the "to" field.
Thanks for any help!! | Gravity Forms will be your solution, but you will have to do some custom notifications.
You will also need User Registration Add-On the <
What you will need to do is:
1. Create a hidden field called for example "current user email" and allow it to be populated automatically.
2. Create a user registration feed and select Update User Option
3. Link this field with logged in user meta info - this will populate the form with current logged in user email address
4. Create a new notification template on submission and select option Email to -> Select a field -> Send To a Field -> Your hidden field. Screenshot: <
5. Configure the rest of the email
6. Voilà it works | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, forms, email"
} |
Theme Check reporting an incorrect theme slug and text domain
I was running my theme through Theme Check to check for WP.org compliance and it is giving me a warning that the theme is in the wrong directory. The specific warning is below:
> WARNING: Your theme appears to be in the wrong directory for the theme name. The directory name must match the slug of the theme. This theme's correct slug and text-domain is the-m-x.
However, my theme's text domain is set to `the-mx`, without the dash in between.
In style.css, I have:
/*
Theme Name: The M.X.
...
Text Domain: the-mx
*/
In functions.php:
function the_mx_setup() {
...
load_theme_textdomain( 'the-mx', get_template_directory() . '/languages' );
...
?>
I am trying to figure out why the theme's slug is coming up as `the-m-x` instead. Also, would this prevent a theme from passing review? | Take a quick look at
1. The theme name as defined in style.css, your's is "The M.X.", looks to me as if WordPress is interpreting the name as "the m x" because of the '.' between the m and the x.
2. What is the actual directory name that your theme is installed in? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes, theme review"
} |
Unable to update wordpress
I have created an ECS Instance in Alibaba Cloud using a Marketplace image powered by IGS(Wordpress on Centos 7.4 64Bits). The installation went fine, but when I am updating, I am getting asked for FTP Details which I am not aware.
 issue.
You don't have enough privileges (755 at least) for WordPress to update. This also means you can't write to `wp-uploads` and so on.
Check this out:
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "updates"
} |
Give a user role capability to create orders for clients
I have WP Theme called Traveler, the theme is for hotel booking, it has partners user role, now I have created a new user role called Broker, and want to give this user the option to book rooms for his clients but only to hotels he has been assigned to. is there a plugin that can help me with that? | Have you tried the plugin User Role Editor? < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "user roles, theme customizer"
} |
How to check If Oembed is empty or not
We often use the Oembed function provided by the Wordpress to embed media.
I have a condition where I am running a loop to fetch certain posts from a custom post type, but I want to skip posts in which Oembed is empty.
How to check if Oembed is empty or has a URL in meta of single.php.
I tried something like this →
<?php $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
<?php $embed = wp_oembed_get( $url ); ?>
# PHP Needed →
Now how to check if `$embed` is empty or not?
# Update as requested →
The front end will be like this, and it pulled by running a WP custom loop like this.
But there can be a situation like this where the OEMBED is empty like this.
So what I want is when such situation exists the loop should exclude that post and for that, we need `if condition` that checks If oembed is empty or not.
` only works for supported oEmbed providers. The return value is also is a URL of false, as mentioned per codex:
> If $url is a valid url to a supported provider, the function returns the embed code provided to it from the oEmbed protocol. Otherwise, it will return false.
Therefore, is the input is empty, the return value would be false, so you could simply check:
if ( $embed ) {
// Valid
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "php, functions, videos, oembed"
} |
Parse error: syntax error, unexpected '}' on get_the_author_meta
<?php if(!empty(get_the_author_meta('facebook',$part_cur_auth_obj->ID))){?><a href="<?php echo get_the_author_meta('facebook',$part_cur_auth_obj->ID);?>"><i class="fab fa-facebook-f"></i></a><?php}?>
I put the above code on line one (originally on line 90 something and errored there as well) and got an error in my `author.php` template on that line.
> Parse error: syntax error, unexpected '}' in author.php on line 1
Note: `$part_cur_auth_obj` is just my particular theme's author object.
Can someone explain what I'm doing wrong? Is it something particular to `get_the_author_meta`? I appear to have the right amount of parens and curly braces according to my editor... so I'm not sure why the `}` is unexpected.
I know there are alternative syntax for `if/else` but I tried those too and it didn't work, so I'm not sure what is going on.
It also appears according to this - < \- that both syntax should work. | Let's unwrap it to more readable form:
<?php
if ( ! empty( get_the_author_meta( 'facebook', $part_cur_auth_obj->ID ) ) ) {
?><a href="<?php echo get_the_author_meta('facebook', $part_cur_auth_obj->ID);?>">
<i class="fab fa-facebook-f"></i>
</a><?php}?>
End the last line is a problem. There are no spaces around curly bracket and it causes the error. Just change it to `<?php } ?>` and it will work fine.
So the rule is that you should put a space after `<?php` tag - it will cause problems otherwise. You can read more on this topic here: <
PS. If you combine PHP and HTML, it is better to use : notation for blocks and not brackets, I guess. It's easier to keep track with all those `endif`s, `endwhile`s and so on than with a lot of `}`. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php, query"
} |
media_handle_upload for local files?
I am creating an image on the server and storing it in a tmp folder. I would like to run a php file that takes this image, stores it in the default media directory structure and attaches it to a post while creating appropriate thumbnails. media_handle_upload seems to require an upload POST request to work with. Is it possible to make it work on a local image in a non-POST context? Thanks. | You want `media_handle_sideload()`
> Handles a side-loaded file in the same way as an uploaded file is handled by media_handle_upload().
// Array similar to a $_FILES upload array.
$file_array = array(
'name' => 'filename.jpg',
'tmp_name' => 'path/to/filename.jpg',
);
// Post ID to attach upload to, 0 for none.
$post_id = 0;
$attachment_id = media_handle_sideload( $file_array, $post_id ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "posts, post thumbnails, attachments, media"
} |
Can't access admin dashboard with wp-admin without /index.php after it
After I log in, I'm redirected to `example.com/wp-admin/`, which has a "ERR_TOO_MANY_REDIRECTS" message. If I type in `example.com/wp-admin/index.php`, everything works just fine. My `wp-config.php` looks fine. This is not a multisite setup.
My `.htaccess` has the following:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Disabling all plugins, changing theme, and hard code siteurl and home values in `config.php` did not solve the issue.
Any ideas how to fix this? | It sounds like Apache's `DirectoryIndex` may be set "incorrectly". Try resetting this at the top of your `.htaccess` file:
DirectoryIndex index.php | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "wp admin, redirect, login, htaccess"
} |
get_terms in a taxonomy template
I've two custom taxonomies, and two template archives: taxonomy-brand.php and taxonomy-producer.php
If I insert `$terms = get_terms('brand');` in the taxonomy-producer.php I can't get terms for the taxonomy `brand`. If I write something like `echo $terms->slug;`, it doesn't show anything. | `get_terms` returns array of terms and not only one term, so you can't do `$terms->slug`, because it makes no sense at all...
If you want to display all terms, you'll have to loop through them:
$terms = get_terms( array(
'taxonomy' => 'brand',
'hide_empty' => 0
) );
if ( ! is_wp_error($terms) ) { // it can return WP_Error
foreach ( $terms as $term ) {
echo $term->slug;
}
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "custom taxonomy, terms, archive template"
} |
Customizing the Wordpress login form
using this doc from WordPress I was able to remove the default WordPress logo and add my own using
function my_login_logo() { ?>
<style type="text/css">
#login h1 a, .login h1 a {
background-image: url(<?php echo get_stylesheet_directory_uri(); ?>/images/site-login-logo.png);
height:65px;
width:320px;
background-size: 320px 65px;
background-repeat: no-repeat;
padding-bottom: 30px;
}
</style>
<?php }
add_action( 'login_enqueue_scripts', 'my_login_logo' );
The link to the WordPress site, not my site, is still there
<h1><a href=" title="Powered by WordPress">Your Site Name</a></h1>
What I am wanting is more like this
<h1><a href=" title="<?PHP get_bloginfo( 'name' ); ?>"><?PHP get_bloginfo( 'name' ); ?></a></h1> | Try the following filters in your `functions.php`
//wordpress.org > your link
function wp_305258_login_url() {
return home_url();
}
add_filter( 'login_headerurl', 'wp_305258_login_url' );
//alt text to your site name
function wp_305258_login_title() {
return get_option( 'blogname' );
}
add_filter( 'login_headertitle', 'wp_305258_login_title' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "login, wp login form"
} |
Wordpress custom post type permalink: website.com/post-name/post-id
I am trying to build a custom permalink in wordpress for my custom post type `artikelen` (exact slug). I found code online and it seems to do the work with transforming the links with a custom structure `%postname%/%postid%`, but when I save my permalinks and go to a detail page I get a 404 error.
I am posting my code to demonstrate my way of working.
add_filter('post_type_link', 'wpse33551_post_type_link', 1, 3);
function wpse33551_post_type_link( $link, $post = 0 ){
if ( $post->post_type == 'artikelen' ){
return home_url( $post->post_name .'/'. $post->ID );
} else {
return $link;
}
}
add_action( 'init', 'wpse33551_rewrites_init' );
function wpse33551_rewrites_init(){
add_rewrite_rule(
'product/([0-9]+)?$',
'index.php?post_type=artikelen&p=$matches[1]',
'top' );
} | product/([0-9]+)?$
translates to `product/` followed by any number or nothing (and nothing more, not even a trailing slash). This doesn't sound like the thing you want to achieve.
Instead, try the following
function wpse33551_rewrites_init(){
add_rewrite_rule(
'^([^/]+)/([0-9]+)/?$',
'index.php?post_type=artikelen&p=$matches[2]',
'top'
);
}
which translates to:
* `^` start of the string (ie, there is nothing else in front)
* `([^/]+)`: at least one character that is not `/`
* `/`: a slash
* `([0-9]+)`: at least one number
* `/?`: zero or one (trailing) slash
* `$`: end of the string | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, permalinks, url rewriting, rewrite rules"
} |
And I click on a menu item and it leads me to nowhere
On my WP LP I have a menu where if you click on an item you would have been scrolled to a relevant place on the LP, on this one page, but if I'm on another page and I click on a menu it leads me to nowhere, it just stands still and does nothing because now after domain goes slash and the slug of the page and only here goes my #ID - < if I click item Этапы. So I need when I click it the slug after domain disappears and be like < How to achieve it? | In each menu item set the URL to `/#yourid` instead of `#yourid`. That way it points to the ID on the homepage, not on the current page/post/cpt. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "menus"
} |
Break out of wordpress filter
I am using the following hook to loop over my menu items and apply a class based on certain criteria.
add_filter( 'nav_menu_css_class', 'highlight_base_category', 1, 3 );
The `nav_menu_css_class` filter runs for each individual menu item, but I want to completely halt the filter once the class has been applied to one menu item, to prevent more than one menu item having the same class.
I've been looking at setting a global boolean, or using a session, but it seems messy.
Is there a way of breaking out of the filter for the entirety of the current page request, or a global flag i could set and check each time a menu item is filtered? | Yes, there is such way. All you need to do is to unregister your filter inside it:
function highlight_base_category( $classes, $item, $args ) {
// most probably you have some if statement here
if ( /* YOU CONDITION */ ) {
// your code
remove_filter( 'nav_menu_css_class', 'highlight_base_category', 1 );
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'highlight_base_category', 1, 3 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters"
} |
Correct function to get the user's latest Woocommerce Subscription?
I've a members' only subscription site, where the member can only have one active subscription, and I need to be able to get the status of the subscription.
I've been through all the documentation and found the `wcs_get_users_subscriptions()` function, which returns an array of all subscription products for the given user, in reverse date order (ie, latest is always first).
I settled on this code which, whilst it works, I know is absolutely the **wrong way** to do it:
$subs = wcs_get_users_subscriptions( $user_id );
$subs = (object) array_shift( $subs );
$subs = (object) $subs->data;
$return = $subs->status;
Does anyone know the right way? | use this code
$users_subscriptions = wcs_get_users_subscriptions($user_id);
retrieve the data using foreach
foreach ($users_subscriptions as $subscription){
if ($subscription->has_status(array('active'))) {
echo $subscription->get_id();
}
}
> There is some function to access subscription data. like get_id(),get_date('end') (to get last date of subscription ).
I hope its help you well. | stackexchange-wordpress | {
"answer_score": 11,
"question_score": 8,
"tags": "woocommerce offtopic, subscription"
} |
Prepend regular Posts with custom slug, without affecting Custom Post Types?
My company policy is to prepend "/blog/" to our Post slugs. Normally our SEO team will do this via the Custom Permalinks setting (/blog/%postname%), but this has the side effect of pre-pending /blog/ to other Custom Post Types as well.
I know I can set the `with_front` attribute to `false` when registering Custom Post Types to avoid this issue, but it's quite a pain when Themes add their own Custom Post Types, or if we inherit sites from other developers.
Has anyone else run into this issue, and if so, how do you get around it? | Use the `register_post_type_args` filter to alter post types registered by code you don't control.
You can set it for a specific type:
add_filter( 'register_post_type_args', 'wpd_change_post_type_args', 10, 2 );
function wpd_change_post_type_args( $args, $post_type ){
if( 'turnips' == $post_type ){
$args['rewrite']['with_front'] = false;
}
return $args;
}
Or remove that `$post_type` check to change it for all custom types. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "custom post types, blog"
} |
Custom Page that comes with preloaded content for the user
Sorry if the question isn't all clear, but I have been struggling with the keyword for this, probably there's a keyword for it that I don't know of. The Wordpress site I'm developing at this moment is for a scientific project, and the writers are student researchers. Thing is, when they are writing their scientific assessments, it would be really helpful for them to use a certain type of format that comes preloaded with the page or blog type, but since I don't know a keyword for it, I'm struggling a bit to find anything regarding it.
Perhaps a better explanation: I click "Add New Page" or "Add New Post", and when the editor shows up, it has some contents in there already that just need to be extended, instead of having to type all of it again.
How one would go by developing it?
Hopefully my question and explanation is clear enough. Thanks! | You can do this like this: (answering from mobile. Please forgive if the markup is broken)
add_filter( 'default_content', 'preloaded_editor_content', 10, 2 );
function preloaded_editor_content( $content, $post ) {
switch( $post->post_type ) {
case 'your_post_type':
$content = 'your content';
break;
default:
$content = 'your default content';
break;
}
return $content;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, customization, page template"
} |
How to hide/remove featured images in particular categories post?
I have multiple posts in three categories.
The categories are
1\. News
2\. Images
3\. **Videos**
If i click any post that Post's Feature image was shown in top of the article. But other two categories is ok but in **Videos** category i dont want to display feature images. Is there any way to do this..
(Note: I am setting feature images for videos category because i am using that image in different place. So i cant remove this. So tell some solution to hide image when viewing post) | I assume that all your posts are come from single.php. WordPress provides has_category() function to check if post has specific category.
So your code on single.php will need to be like something in given below
if( !has_category('video') ){
the_post_thumbnail();
}
where it checks if post has 'video' category. And if it is false then the feature image will be displayed. otherwise, it can't. Hope it will be help you. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "categories, post thumbnails"
} |
Custom RSS feed with custom url
I'm trying to create custom RSS feed that will contain one post type and posts there from just one category. URL to this feed should be `/rss`.
I tried some plugins but didn't found any that will help me with this. Also, I used some plugin to disable feeds from core because I don't need them anymore.
Is there some way to achieve this and how? Some plugins or examples would be great. | Yes, it is possible to customize feeds. In your case, what you want to do is disable to normal rss feed and replace it with a template of your own. Like this:
remove_action ('do_feed_rss','do_feed_rss',10,1);
This line is a bit confusing. The first `do_feed_rss` is the name of the action hook. The second is the default function on that hook. Now you can add a new action:
add_action( 'do_feed_rss', 'wpse305438_custom_rss', 10, 1 );
function wpse305438_custom_rss () {
load_template( TEMPLATEPATH . '/my-custom-feed.php');
}
Beware that by default WordPress will relay `/rss` to `/feed`. Changing that involves hooking into `rewrite_rules_array`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "rss, feed"
} |
Can I create custom taxonomy what dont creates slug pages?
I want assigned a value to my posts what variable by the current post's id. Originally I want use custom post_meta for this, I think this is would been elegant, but when I run a query with this post_meta, my pageload will be horrible slow (4x-5x the basic time), because the sql query (I create an own index in my database for this post_meta, but this dont help for me)...
So, I read that, If I create a custom taxonomy, what have the same values, this will be fast, like tag queries. But I dont want that, if this custom taxonomy creates pages (domain(.)tld/taxonomy_name/taxonomy_slug)...
Can I create custom taxonomy without pages? So that this going to works like that a post_meta? Only a value, what queried? | It depends on what exactly you want, but you can play with `public`, `publicly_queryable` and other arguments when registering the taxonomy.
For example, with the following code, the taxonomy will have the user interface in the backend, but won't be public and WordPress won't generate a URL for each term:
add_action( 'init', 'register_custom_tax' );
function register_custom_tax() {
register_taxonomy(
'my-tax',
'post',
array(
'public' => false,
'show_ui' => true
)
);
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom taxonomy"
} |
img src not working correctly in custom post type
I am new to wordpress. i have a raw html box in my page having img link
`<button><img src="./wp-content/uploads/2018/05/video-popup.png" ></button>`
it shows img url as **''mysite/beta/wp-content/uploads/2018/05/video-popup.png"** when i use same in custom post type it shows a **404 error** with the url link **''mysite/beta/dictionary/a/wp-content/uploads/2018/05/video-popup.png"**
dictionary is the post type and 'a' is the page of dictionary type. kindly help me out of this how to get rid of this issue | Add this following function to your functions.php of your theme or child theme.
function homeURLshortcode()
{
return home_url();
}
add_shortcode('homeurl', 'homeURLshortcode');
This will create a shortcode like `[homeurl]` which you can use to add in any visual editor and it will render as your main domain address, like <
So for your image url you need to add `[homeurl]/wp-content/uploads/2018/05/video-popup.png` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "custom post types, images, urls"
} |
How to build a dynamic data table with backend fields for the user
Since i am very new to wordpress, what is the best way to create a custom dynamic data table that a user can add/modify or delete data from the backend? what i need as a final table is something like:
* Logo(an image) | Brand(text) | offer(text) | link(text)
and pulled somewhere in the homempage. i tried to create a custom plugin, it seems a bit advanced for me, and don't actually know if it is what i am looking for. i also played with advanced custom fields but only managed to store each brand in a post instead of a row...
thank you in advance
EDIT: Yes you are right! ACF can do this using the repeater field < | Advanced Custom Fields Pro lets you add an options page to the WordPress backend. Then you can create your fields for site-wide options (i.e. logo, branding options, etc) on a dedicated options page and pull them from anywhere on the site, rather than only from within specific posts/post types. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "table"
} |
How to get User Avatar Image with link to Author and User name in Html Title tag?
I'm wondering how could I achieve this result mixing the avatar image with href to author page and also when the mouse is over the image, show in "html title tag" the name of the user?
I know I can do this all alone, like using the get_avatar_url and using the get_avatar and get_the_author, like this below:
echo get_avatar( get_the_author_meta( 'ID' ), 32 );
$author = get_the_author(); echo $author;
How can I do this? I didn't understand how the apply_filter works in Wordpress, I know there is $alts where I could modify the HTML, but I don't know how (no examples in the web).
BTW: This is gonna be used in The Loops section. | My god :P
It was as simple as html tags, I just didn't know the correct wordpress functions to use.
Here it go, for future reference:
<a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ), get_the_author_meta( 'user_nicename' ) ); ?>">
<img src="<?php echo get_avatar_url( get_the_author_meta( 'ID' ) ); ?>" title="<?php echo get_the_author(); ?>">
</img></a> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, gravatar"
} |
Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH) in
<ul class="project-extension-side-link">
<?php foreach($projectextensions as $projectextension){?>
<li <?php if($section=='project-extension')
{echo 'class="active"';}>><span>Project 1</span></li>
<li><a href=""><?php echo $projectextension->post_title; ?></a></li>
<li><a href="">Project 3</a></li>
<li><a href="">Project 4</a></li>
<li><a href="">Project 5</a></li>
<li><a href="">Project 6</a></li>
</ul>
<?php endforeach;?>
<?php}?> | When you use `endforeach;`, you have to use `:` instead off `{` when starting the `foreach`.
<ul class="project-extension-side-link">
<?php foreach($projectextensions as $projectextension) : // <--- ?>
<li <?php echo ($section=='project-extension' ? 'class="active"': ''); ?>><span>Project 1</span></li>
<li><a href=""><?php echo $projectextension->post_title; ?></a></li>
<li><a href="">Project 3</a></li>
<li><a href="">Project 4</a></li>
<li><a href="">Project 5</a></li>
<li><a href="">Project 6</a></li>
<?php endforeach; ?>
</ul>
Greetz Bjorn | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "functions, loop"
} |
trouble with parse error
thanks in advance, I'v added `mobile detect` library to my wordpress site (its a pre made theme with a child theme ).
I'v tried to run these code, but i'm keep on getting this error, I'v searched this group there are lots of answers none worked for me
`Parse error: syntax error, unexpected '<'`
what am I doing wrong ? thanks to all library site
<?php if ( $detect->isMobile() ) {
<div>
<?php wc_get_template_part( 'checkout/layouts/test.php' ) ?> ;
</div>
} ?> | Assuming the logic is correct, the fault lies in your PHP syntax. This would be correct:
<?php if ( $detect->isMobile() ) { ?>
<div>
<?php wc_get_template_part( 'checkout/layouts/test.php' ); ?>
</div>
<?php } ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
WP Query Leads to 502 Bad Gateway (Timeout Because Query Takes Too Long)
Why does this simple query break my site and lead to the following error:
> 502 Bad Gateway
I am using the category `slug` and yes I have exactly **one** post of this category. It is embedded in the header template part of a third-party theme.
function bambam(){
$args = array(
'category_name' => 'breaking-news',
'post_date' => 'DESC',
'posts_per_page' => 1
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
echo '<div class="breaking-news">';
while ( $the_query->have_posts() ) {
echo '<h1>' . get_the_title() . '</h1>';
}
echo '</div>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
}
bambam(); | It has nothing to do with WP_Query itself. The reason for such problem is what you do with this WP_Query. There’s no `the_post()` in your code, so the loop is infinite.
This is how to fix it:
function bambam(){
$args = array(
'category_name' => 'breaking-news',
'post_date' => 'DESC',
'posts_per_page' => 1
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
echo '<div class="breaking-news">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<h1>' . get_the_title() . '</h1>';
}
echo '</div>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
}
bambam(); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, loop"
} |
How to add a class to a link in text editor
The editors of my web are absolute noobs :) They don't now anything about CSS an HTML. Therefore I have a question:
Some links should get a class for styling them as a nice button. Is it possible to enhance the WP text widget link section by adding a simple checkbox "Link is a super-special button"? And when checked the button a class is added to the a tag?
 {
if ( is_product() || is_cart() ) {
remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );
}
}
add_action( 'woocommerce_before_main_content', 'urun_sidebar_kaldir' );
It works in single-product page, but it doesn't work cart page.
I can't remove sidebar in cart page.
**//Update**
I am not using **woocommerce.php** in theme main folder.
And i have this templates in my theme.
wp-content/themes/{current-theme}/woocommerce/cart/cart.php
I created custom teplate for cart. And i removed **get_sidebar();** but sidebar is still displaying in cart page.
wp-content/themes/{current-theme}/page-cart.php
wp-content/themes/{current-theme}/page-checkout.php | First, most themes have multiple page templates you can choose from.
Please check:
1. go to cart page (in wp-admin).
2. See side metabox 'Page Attributes'.
3. There you can set the page template, does it have something like 'full_width'?
You can also try a different hook, like `wp_head`.
Example:
add_action( 'wp_head', 'urun_sidebar_kaldir' );
Let me know.
* * *
After checking the WOO cart template, i can't find a `do_action( 'woocommerce_sidebar' )`. It does exist in the singe-product.php template.
Are you certain the cart sidebar is generated by WooCommerce?
* * *
Add a full-width template to your theme:
Read this.
Then follow the steps i mentiod at the beginning of my answer. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "woocommerce offtopic, sidebar"
} |
How to change the blog title with add_filter? details below
i want to add a prefix to all the blog title by modifying the all ready applied filter .
when i searched i got this:
apply_filters( 'single_post_title', string $post_title, object $post )
what action do i have to modify this?
add_filter('single_post_title', 'my_title');
function my_title() {}
i want this done without the javascript .. any help is really appreciated thanks | With the filter `single_post_title`, you can change the page/post title that is set in the `<head><title>Page title</title></head>`.
If you want to change the title that you see in the page header. ( Which i think you want to do).
Use this filter:
add_filter('the_title', 'modify_all_titles', 10, 2);
function modify_all_titles($title, $id) {
return 'SOME TEXT BEFORE TITLE | '.$title;
}
Place this code in the functions.php (use a child theme).
Regards, Bjorn | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "filters, actions, blog"
} |
How to validate website field in contact form 7?
Is there any way to validate website field entered is right or wrong through Contact form 7?
Please help me. | Yes, you can add your own custom validation. More info here.
* * *
Here's a working and tested example for your situation:
Use `[text* your-website]` inside your contact form 7 form.
Add this snippet to your theme's functions.php, use a child-theme!
add_filter( 'wpcf7_validate_text*', 'custom_website_validation_filter', 20, 2 );
function custom_website_validation_filter( $result, $tag ) {
if ( $tag->name == 'your-website' ) {
$domain = isset( $_POST['your-website'] ) ? trim( $_POST['your-website'] ) : '';
if ( ! checkdnsrr($domain, 'ANY') ) { // Check DNS records corresponding to a given Internet host name or IP address
$result->invalidate( $tag, "We cannot find an active dns record for that website url?" );
}
}
return $result;
} | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "email, plugin contact form 7"
} |
Woocommerce Setup not completing
While trying to install an existing site on my localhost, i am finding this weird error. I can login in the dashboard. After that I can not go to any other links. The woocommerce setup wizard shows always.
I have tried to skip the setup by pressing not now and also tried to setup the woocommerce. But nothing seems to work.
Is there anything I can do to fix this problem? | After some digging in WooCommerce I found the filter `woocommerce_enable_setup_wizard`:
add_filter('woocommerce_enable_setup_wizard', function(){return false;},999);
Add that line to your (child) theme functions.php
Let me know if it works.
NOTE: this is just a 'patch'. Woocommerce should not behave like this, most likely you will get more errors along the way.
Regards, Bjorn | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
how to change comment author's link from user's website to author's page(author.php)?
I am making theme. and in my custom post type comment, I using
wp_list_comments( array(
'style' => 'div',
'short_ping' => true,
'avatar_size' => 0,
'reply_text' => 'reply',
) );
This works good. but, when I click the user's name(who wrote the comment), this makes move to his website. But I want to move to his author's page(author.php).
Is this possible? Can you give me some help? Thank you. | There are many ways to do this.
## Using `callback` param
One of methods would be using the `callback` param of `wp_list_comments`.
This function takes 3 params: `$comment`, `$args` and `$depth` and using it you can create custom HTML code for comments.
There is an example showing how to use this callback in Codex or you can find such callbacks in TwentyX themes.
## Using `get_comment_author_url` filter
But if you want to modify only the URL for authors, then there's an easier and cleaner way and I would definitely prefer this solution.
You can use `get_comment_author_url` filter as showed below:
function use_author_link_as_comment_author_url( $url, $id, $comment ) {
if ( $comment->user_id ) {
return get_author_posts_url( $comment->user_id );
}
return $url;
}
add_filter( 'get_comment_author_url', 'use_author_link_as_comment_author_url', 10, 3 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "comments"
} |
How to add filter in custom rss feed
I have this code for my 2 custom rss feeds:
add_action( 'init', 'custom_feeds' );
function custom_feeds()
{
foreach( array( 'custom1', 'custom2' ) as $name )
{
add_feed( $name,
function() use ( $name )
{
get_template_part( 'rss', $name );
}
);
}
}
function feedFilter($query) {
if ($query->is_feed) {
$query->set('cat', '7');
$query->set('posts_per_page','5');
}
return $query;
}
add_filter('pre_get_posts','feedFilter');
I wanted to put filter on `custom2` only, like filter the feed by `category 7` only; But my filter is affecting all the rss feeds. | As you can see from the source `is_feed` takes a parameter, so you should be able to restrict the query by using `$query->is_feed('custom_rss2')`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, rss, feed"
} |
wordpress images not display
my .htaccess code
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Can anyone help me ?
Thanks | The solution is arrived with the 4.9.7 update of WordPress. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "html"
} |
Updating all rows of table with $wpdb
how to update all rows of an table with $wpdb? I tried this, but won't work:
$wpdb->update( 'wp_comments, array( 'comment_karma' => '123' ), null );
and this
$wpdb->update( 'wp_comments, array( 'comment_karma' => '123' ), array() );
So how to do this? Thanks in advance! | It will not work as the update statement requires a selector to narrow down what to update. You should use a general query. For your needs use this:
$wpdb->query(
$wpdb->prepare(
"UPDATE $wpdb->comments
SET `comment_karma` = %s",
'123'
)
); | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "database, wpdb"
} |
Customize WP website specific column with CSS
I would like to change the following sentence “CREATING STYLE FOR BETTER LIFE” to a different font (Rochester) and i have tried several CSS codes so far but none has worked for me so far.
Website: <
Please tell me what CSS code should i use and where to apply it
Thanks | Include Rochester font from Google
<link href=" rel="stylesheet">
See wp_enqueue_style() or maybe you can use your theme (set font rochester to a heading you dont use for example).
Add a class to that h2:
<h2 class="rochester-font">CREATING STYLE FOR BETTER LIFE</h2>
In your CSS:
.rochester-font {
font-family: 'Rochester', cursive;
/* other css */
}
Don't forget the browser caching! Use hard-refresh when you're testing CSS.
Regards, Bjorn | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "customization, css"
} |
How can I load an inline script after the enqueued scripts in admin?
I am having a heck of a time finding an answer to this solution. I have googled everything I can think of but I can't find anything. I want to load an inline JavaScript tag in the footer of the admin. When I use the admin_footer action, the code is added _before_ the JS tags that are called by the wp_enqueue_script function. I need this script to be called _after_ those scripts. How can I achieve this?
This is what I am using now:
<?php add_action('admin_footer', 'gallery_js', PHP_INT_MAX);
function gallery_js(){ ?>
<script>
(function($){
$('#deleteSelected').serviceGallery({
ajaxUrl: '<?php echo JZS_PLUGIN_PATH.'/admin/partials/service-gallery-ajax.php';?>'
});
})(jQuery);
</script>
<?php }
See this image for a better explanation: ;
function my_save_post_function( $post_ID, $post, $update ) {
error_log($post_ID );
error_log( print_r( $post_ID , true ) );
}
I also enable this in wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true); | The action `save_post` gets triggered after a post is saved, not after a user is saved. For this you need the action `profile_update`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users"
} |
Gutenberg - remove / add blocks with custom script
I’m currently testing the new Gutenberg plugin with my own developed theme and plugin. My theme has a custom meta box with an action for the user. Once the user click this action the post content is completely deleted and a new ‘custom’ content is added to the default tinyMce editor.
**_Example** : tinymce.get(“content”).setContent(“my custom content”);_
This of course does not work anymore with the new Guteberg Editor and I’m struggeling to find a solution.
So Basically what I’m trying to do is to remove all block/content from the gutenberg editor and add a new block (text) with my custom content via javascript. Does anyone have any hint to point me in the right direction? | There's probably a simpler way to do this, and if there isn't you should open an issue on the Gutenberg GH issue tracker ( the API is not set in stone ).
**Because the API is not set in stone, this answer may be useless when it's finally done and merged. The first and best place to ask GB questions is on GitHub**
You can eliminate all blocks using this:
wp.data.dispatch( 'core/block-editor' ).resetBlocks([]);
You can then create a new block programmatically:
let block = wp.blocks.createBlock( 'core/paragraph' );
Add text to it:
block.attributes.content.push( 'hello world' );
And insert it like this:
wp.data.dispatch( 'core/block-editor' ).insertBlocks( block );
* * *
**On further inspection, there's a simpler method:**
let block = wp.blocks.createBlock( 'core/paragraph', { content: 'test' } );
wp.data.dispatch( 'core/block-editor' ).insertBlocks( block ); | stackexchange-wordpress | {
"answer_score": 16,
"question_score": 10,
"tags": "javascript, block editor"
} |
Get the link for RSS item to display in feed
function wpbeginner_postrss($content) {
global $wp_query;
$postid = $wp_query->post->ID;
if(is_feed()) {
$coolcustom = get_field('fl_quote');
$link = the_permalink_rss();
$content = '<div>' .$coolcustom. '</div></br><div>This post first appeared on My site - read more at <a href="'. esc_url($link) .'">' . get_the_title_rss(). ' →</a>';
}
return $content;
}
add_filter('the_excerpt_rss', 'wpbeginner_postrss');
add_filter('the_content', 'wpbeginner_postrss');
For some reason the link is displayed empty inside the RSS feed. Is there something wrong with the way I obtain the $link ? | The `the_permalink_rss()` is `echo`ing it's content not `return`ing it.
If we look at the source of this function: <
We can just copy what it's doing, as it's a simple function.
`$link = esc_url( apply_filters( 'the_permalink_rss', get_permalink() ) );` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, rss"
} |
wp_enqueue_scripts are apearing inline rather than as links
I'm not sure whats going on with my code here, I'm enqueuing scripts like so:
wp_enqueue_script( 'lightbox', '/wp-content/themes/'.get_stylesheet() . '/js/lightbox.js');
However when I view the source of my page, the script isn't being linked, rather all the js is being loaded into the head of the document like so:
<script type="text/javascript" style="display:none"><!--
/*!
* Lightbox v2.9.0
* Released under the MIT license
*
*/
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],b):"object"==typeof exports?
etc...
Is this the correct behavior? It seems to be causing conflicts with my other scripts? Many thanks. | You should not use relative URLs when enqueuing media items. Use the full URL instead.
There are two functions that can come in handy: `get_theme_file_uri()` and `get_template_directory_uri()`.
So:
wp_enqueue_script( 'lightbox', get_theme_file_uri( '/js/lightbox.js' ) );
will be the correct syntax. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp enqueue script"
} |
How do I display certain products via their category on a section of a page using PHP?
I need to display New Arrivals in a section of my homepage, I have created a new arrivals category and would like to display the products in this category on a page, I don't want to use the shortcode as I am writing the html & php for this page.
Any help would be appreciated, thanks. | you can still use a shortcode inside of php if you aren't customizing the output. see < and <
<?php
echo do_shortcode('[products category="new-arrivals"]');
?>
Alternatively, If you need to customize the output of the products then just use `wc_get_products` to get a list of products and iterate through it. See <
<?php
$args = array(
'category' => array( 'new-arrivals' ),
);
$products = wc_get_products( $args );
foreach ($products as $product) {
echo $product->get_title() . ' ' . $product->get_price();
}
?> | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 3,
"tags": "woocommerce offtopic"
} |
how to change the max size of media upload? video audio wp 4.9.6
I'm using wordpress 4.9.6, and the max file size upload is now 8Mb. I used to upload 50+Mb video and audio, but it has changed. how can I change that to 100Mb? | It is something you can increase in your php.ini settings with your host server admin. I've found this resource for you: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads"
} |
Add another feature image box
I already have featured image box in my wp theme.
So what I want:
I want to add another featured image box at the top of my category section with different name something like custom featured image.
Why I want to do:
I want to do so because I want to use another featured image box for a specific purpose.
But don`t want to use any plugin please | Finally I did it by using custom fields with out any plugin. Thanks to Tania Rascia Custom field post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, images, post thumbnails"
} |
Rewrite /?rest_route=/ link to /wp-json/ without changing default permalink structure in apache
How to rewrite url of wordpress rest api from `< to `< without changing (default) permalink structure? Need this for apache (htaccess).
In nginx it would be like this:
`location ~ ^/wp-json/ { rewrite ^/wp-json/(.*?)$ /?rest_route=/$1 last; } ` | Solved by this lines:
RewriteEngine On
RewriteBase /
RewriteRule ^wp-json/(.*) /?rest_route=/$1 [L] | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 3,
"tags": "htaccess, rewrite rules, rest api, apache"
} |
Highest number of WordPress Custom Page Templates?
I'm little bit rookie in understanding WordPress core. But I would like to know that, is there any limit or should we limit to how many custom "page" templates we make in our custom theme?
My WordPress website is currently using about 50 custom coded page templates, I would like to know its performance, side effects and when should I stop creating these templates and restructure the whole website so that it uses less templates.
Also each template provides it's unique feature in my scenario, that's the main reason they are distributed seperate template files. | I don't think there is such limit. Of course you can't say it's unlimited, because in IT everything has some limits (due integer size, number of files in directory, maximal length of filename, and so on).
There won't be any big performance side effects. WordPress stores list of templates in cache (AFAIR), so it should be OK. (Of course again, if you'll create 1000000 templates, then the select on page editor will take long time to load...)
But, there is one limit - will the user be able to select proper template. And are these templates really necessary - maybe there should be some options in the editor to modify the look and feel of given template, and so on. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "theme development, pages, page template"
} |
add_cap not working with Shop Manager role
I'm running WooCommerce and have added a user with the role 'Shop Manager'.
I'd like the Shop Manager to have the ability to add users.
Here's my code:
function shop_manager_add_users() {
$role = get_role( 'shop_manager' );
$role->add_cap( 'add_users' );
}
add_action( 'admin_init', 'shop_manager_add_users');
However, when I log in as the Shop Manager, they are still unable to add users. What am I doing wrong here? | add_users capability is only used for backward compatibility. so we should use create_users capability instead of add_users capability. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "users, user roles"
} |
show posts with range meta key
i want to show posts with age between 5 and 10 usind WP_Query.how i can do this?
$args = array(
'post_type' => 'my_custom_post_type',
'meta_key' => 'age',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'age',
'value' => array( 3, 4 ),
'compare' => 'IN',
),
),);$query = new WP_Query( $args ); | You can compare BETWEEN in the `meta_query` and you need to set the type too for NUMERIC.
For example
$args = array(
'post_type' => 'my_custom_post_type',
'meta_key' => 'age',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'age',
'value' => array( 5, 10 ),
'compare' => 'BETWEEN',
'type' => 'NUMERIC'
)
));
$query = new WP_Query( $args ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query"
} |
Can not include file from plugin into theme
I want to include file from a plugin to templates function file. This is the code i use :
$acf_url = plugins_url('/advanced-custom-fields/acf.php');
include_once($acf_url);
But this code is not working and i'm getting this error :
Warning: include_once( failed to open stream: HTTP request failed! HTTP/1.0 500 Internal Server Error in G:\MAMP\htdocs\wp-content\themes\mytheme\functions.php on line 3
Warning: include_once(): Failed opening ' for inclusion (include_path='.;C:\php\pear') in G:\MAMP\htdocs\wp-content\themes\mytheme\functions.php on line 3
So what is the codes problem ? | This is because you are trying to include a directory by URL, you need to call path, you can use the constant `WP_PLUGIN_DIR`. Modifying the variable acf_url to the following would work.
$acf_url = WP_PLUGIN_DIR . '/advanced-custom-fields/acf.php'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "include"
} |
what's different between wpdb->prefix and table_prefix
what's different between wpdb->prefix and table_prefix i want to install db table of my plugin for example
$wps_user_visits_table_prefix = $wpdb->prefix.'wps_user_visits';
is equal to
$wps_user_visits_table_prefix = $table_prefix.'wps_user_visits';
or diffrent ? | The difference is pretty simple.
`$wpdb->prefix` is getting the `prefix` field from global `$wpdb` object.
`$table_prefix` can be anything. Most probably it's some local variable that contains the same value, but you can assign anything to that variable.
So using `$wpdb->prefix` is a better idea - it's nicer, cleaner and more obvious. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development"
} |
How to change the permalink option to post name on theme activation?
Is there any filter to change the permalink structure and set it to post name after theme activation automatically?
i have custom posts but won't work without changing the permalink?
thanks | The flush rewrite rules to be considered while when custom posts are generated.
More info here <
This worked for me as when my theme is activated every thing works file
/* Flush rewrite rules for custom post types. */
add_action( 'after_switch_theme', 'flush_rewrite_rules' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks, filters"
} |
pre_get_posts dont firing... Anybody knows whats the wrong with my code?
I trying exclude category "1" with pre_get_posts:
function exclude_category( $query ) {
if( !is_admin() && $query->is_home() && $query->is_front_page() && $query->is_main_query() && $query->is_tag() && $query->is_search())
{
$query->set( 'cat', '-1' ); // I also trying without the '' on the -1 (cat id)
}
}
add_action( 'pre_get_posts', 'exclude_category' );
I'am use on my pages the main query:
if (have_posts()) : while (have_posts()) : the_post(); | There are a couple of problems with your condition:
A single query cannot match all of your conditions - it can't be a `tag` as well as `search`, for example. You need to use `||` (or) and possibly nest - so for example,
if(!is_admin() && ($query->is_home() || $query->is_search())) {
This says, "if we're not in the admin area AND either it's a home query or a search query, then do this."
Also, some of the `is_` conditions you're trying to meet aren't the way you test the query. `is_front_page()` cannot be called because the query isn't set up yet - but `is_home()` can. Read up in the documentation to learn more about which conditionals are valid, and then you can try a simplified query first - such as `if(!is_admin())` to make sure it's running - then add additional conditions one at a time so you can tell which one specifically is causing you problems. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "pre get posts"
} |
Get Polylang available languages on admin page of my plugin
I am making an plugin, and inside my admin page (Which i add by `add_menu_page()` function) i call this function `pll_the_languages(["raw" => 1]))` but its return nothing,on client side its work fine. I added many languages on Polylang setting page. How can i get Polylang available languages from an admin page ? | According to Polylangs Function Reference, `pll_the_languages`
> Displays a language switcher.
And most probably it uses some additional CSS/JS to work. If you want to get the list of languages and display them with your custom code, then you can use this function instead:
pll_languages_list($args);
and it will return the list of languages.
> $args is an optional array parameter. Options are:
>
> * ‘hide_empty’ => hides languages with no posts if set to 1 (default: 0)
> * ‘fields’ => returns only that field if set. Possible values are ‘slug’, ‘locale’, ‘name’, defaults to ‘slug’
> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "multi language, plugin polylang"
} |
Add Woocommerce product to cart with Contact Form 7
I have a form where people can register for a seminar, which entails filling out your personal info and then selecting which seminar (s) you want to attend, and how many tickets you want to buy. The user would fill it the form and when clicking submit, he is directed to a woocommerce shop page so he can add the desired seminar to his cart and pay for them.
I am trying to get rid of the middle step where the user adds the items to his cart, and would love to use the info from the form to add the respective items to the cart automatically.
I have found the following code which uses the on_sent_ok hook but I believe that is now obsolete and I'm not sure how to use it to add more than one product and quantities from their respective fields in the contact form: `on_sent_ok: "location.replace('
Any ideas of code or plugins would be greatly appreciated! | Add to cart is still working - try
?add-to-cart=ID&quantity=5 | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "woocommerce offtopic, forms, plugin contact form 7"
} |
What Wordpress function to use to get meta value by using meta keys?
This is the code:
if ($keys = get_post_custom_keys()) {
foreach ((array) $keys as $key) {
$keyt = trim($key);
if (is_protected_meta($keyt, 'post')) {
continue;
}
$values = array_map('trim',
get_post_custom_values($key));
$value = implode($values, ', ');
echo " key : ".$key;
echo " value : ".$value;
}
}
The Result:
keyyy : nova_price valueee : $9
My question: Is there a specific Wordpress function to get the meta value `$9` using meta key `nova price`?
I tried using this WP function:
echo" get_post_meta: "; get_post_meta(the_ID(), 'nova_price', true);
but the result is:
get_post_meta: 1872
Any help would be greatly appreciated. Many Thanks. | As the solution suggested in comments worked out for you, I'll just post that as answer over here.
You need to replace `the_ID()` function in your `get_post_meta(the_ID(), 'nova_price', true);` call.
Because `the_ID()` directly outputs the post ID which is then getting printed for you instead of the meta.
Right code would be: `get_post_meta( get_the_ID(), 'nova_price', true)` This should get you the value for _nova_price_ for the given post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "functions, custom field, post meta, meta value"
} |
Remove /product/ from url. I want only category name then product name
I have a site
<
But I want this
Mainly I have to remove /product/ (/shop/) from url.

echo get_the_post_type_description();
How can I get the same description to show on the `single-cpt.php` template?
(ie for every individual post I want to show the description for the archive it belongs to) | Within the loop, you can do it this way, outside of the loop, pass the post ID to `get_post_type` function. :
// Within the loop
$cpt = get_post_type_object(get_post_type());
if($cpt !== NULL)
{
echo $cpt->name;
echo $cpt->description;
}
If you need to see more about `get_post_type_object` you can find it in codex. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "custom post types, templates, archives, single"
} |
Make substitute in all Wordpress posts
I wish to replace one string in all my WP posts (over one hundred).
There is a "bulk edit" feature, but I do not think it covers this feature.
I can think of downloading the database, open it with an editor and make a replace. In a GUI editor this may fail since the file is so large. If I read up on database structure and MySQL I can probably isolate the variable containing the post texts and only edit that one. It is probably best to use a line editor like SED.
At present I don't use MySQL and SED daily and it will take some time to experiment with and also verify that file is OK.
Is there any quick way to make an edit-replace command over all my WP posts?
(The reason I need to do this is that the latest update of "Insert PHP" plug-in does not allow PHP written straight into the pages, which I have used.) | There are many ways to do this here a couple:
1) You can use something like:
Better search and replace plugin here: <
or
SAFE SEARCH AND REPLACE ON DATABASE WITH SERIALIZED DATA script here: <
Both of these with serialize the data, which is important for many themes and plugins.
There is a good explanation of WP Serialized data here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "post editor"
} |
Pre filter woocommerce products to remove a certain category of products
Have differing prices between offline and online using Square (woocommerce plugin) and Woocommerce.
To get around this I was considering a new category for offline and filtering them out of the website and vice versa on the export to Square. Yes there would be duplication of product but independent pricing. Is there a way to hook into the product filter over all website product queries?
I am assuming if so there would be a method for the Square plugin to hook in for the export to do the opposite way.
Which would be the best filter to hook into for Woocommerce? | You can use the `pre_get_posts` hook for Woocommerce product query, but here the example is for the main query.
function wpse_306252_query( $query ) {
if($query->is_main_query()) {
$query->set( 'category__not_in', YOUR_CAT_ID);
}
}
add_action( 'pre_get_posts', 'wpse_306252_query' );
If you want the opposite of it, I think the best is to add a `SquareExport` parameter to check when you want your products.
function wpse_306252_query( $query ) {
if(!isset($_REQUEST['SquareExport'])) {
$query->set( 'category__not_in', YOUR_CAT_ID);
}
}
add_action( 'pre_get_posts', 'wpse_306252_query' );
The last one will always exclude products from `YOUR_CAT_ID`, custom queries, or main query. Hope it fit's your needs :) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "woocommerce offtopic, filters"
} |
How to en-queue bootstrap 4 to theme?
i tried enqueue the bootstap with functions php
wp_enqueue_style('bootstrap4', '
wp_enqueue_script( 'boot1','
wp_enqueue_script( 'boot2','
wp_enqueue_script( 'boot2','
css seems to work but none of the js files are working..not sure what i am doing wrong..
please help thank | You can use action hook and enqueue script and style to the site.
function my_scripts() {
wp_enqueue_style('bootstrap4', '
wp_enqueue_script( 'boot1',' array( 'jquery' ),'',true );
wp_enqueue_script( 'boot2',' array( 'jquery' ),'',true );
wp_enqueue_script( 'boot3',' array( 'jquery' ),'',true );
}
add_action( 'wp_enqueue_scripts', 'my_scripts' );
If you want to add the scripts after jQuery then you can use the jQuery array for dependent and last argument true will include the JS at footer, if you want the js in header, you can remove that. | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "wp enqueue script, twitter bootstrap"
} |
Get posts from the Main site to sub site - Wordpress MultiSites Network
I'm trying to get posts from the main site to sub site using a query but It didn't work
**SITES :** MAIN SITE ID#1 \- Post1 \- Post 2
SUBSITE ID#2 I need to get the Above posts here - Post1 and Post2 | I use this codes to loop over the posts in the Main site:
<?php
$sites = wp_get_sites();
foreach($sites as $site) :
// Only subsites
// Connect to new multisite
switch_to_blog($site['blog_id']);
$case_args = array(
'post_type' => 'downloads',
'posts_per_page' => 1,
'orderby' => 'date',
'order' => 'DESC',
);
$latest_cases = new WP_Query($case_args);
if ( $latest_cases->have_posts() ) : ?>
<?php the_title(); ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query();
// Quit multisite connection
restore_current_blog();
endforeach;
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, multisite"
} |
Woocommerce 2.5.5 get billing email from order instance
I am trying to get the billing email of an order in woocommerce v2.5.5 However its giving me this error:
Call to undefined method WC_Order::get_billing_email()
Here is my order object : print_r($order)
;
$customer_email = $order->get_billing_email();
$shipping_country = $order->get_shipping_country();
$order_items = $order->get_items();
Both get_billing_email and get_shipping_country isn't working.
Condition : I can't upgrade the plugin as the site is really old and i'm 100% sure it'll cost me another 50 to 60 hours to fix everything. Just need a quick fix. | In WC version 2.5, `get` and `set` functions are not available. The parameters you want are public. So, you can directly access them:
$customer_email = $order->billing_email;
$shipping_country = $order->shipping_country;
And so on.
Please check the keys before using them. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "woocommerce offtopic"
} |
Add subdomain for Vue.js application
I want to add a Vue.js and Laravel application to a subdomain of a WordPress main site. How would I best accomplish that?
Thanks in advance! | Assuming the Vue/Laravel app is completely separate from the Wordpress site, the easiest and most basic way to achieve this is just to set the subdomain in your webhosting control panel, and point it to the directory on your webserver where you have uploaded the laravel app.
The webserver makes sure that all requests to subdomain.example.com get handled completely independently from the wordpress site. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "subdomains"
} |
Font awesome Icon HTML in widgets disappear on save
I've created a Text widget and put font-awesome icon HTML in editor Text Mode `<i class="fab fa-facebook"></i>` but toggling to Visual mode makes the code disappears though I can see it working on Frontend. | I think the issue is that WordPress removes empty tags from the editor. Try adding in a non-breaking space - Font Awesome should remove it so you shouldn't see any noticeable difference:
<i class="fab fa-facebook"> </i> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "widgets, widget text, icon"
} |
How to allow user to select page template from front end?
I have post templates ready... I want the user to be able to select the post template from the front end form?
Is there any method or some one could guide me how to achieve this? | You want to use `get_page_templates` function. See codex : <
get_page_templates(null, 'your_post_type'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "page template"
} |
Can my site use two different Wordpress installs for different pages?
I'm currently working on a site that has hundreds of indexed pages, and we want to change the site to a new theme.
Rather than going through and updating every single one of these pages, is it possible for us to do a slow rollout, wherein only some of the pages are from the new Wordpress install, and the rest of the pages are from the old install? Is this a bad idea? Why / why not? Are there good resources online for this sort of thing? I didn't seem to find what I was looking for doing a few different Google searches. Thank you!
So for instance, I want to serve
`www.example.com/page1`
from one wordpress install, and
`www.example.com/page2`
from another Wordpress install.
My understanding is that multisite is not a good solution for this, or is it? | That would be an extremely tricky approach to the problem I think. If your end goal is the replacement of one template with another (a migration), then a more standard approach would be to install an new Wordpress instance on a different URL. Perhaps using < (a subdomain).
This is then your "development", or "staging" server (if a remote server is actually required at all of course.)
Once you replacement work is complete and tested, you would replace the live files with the development files, and complete your migration. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "installation, seo"
} |
Anyone know how to use ACF and show custom fields for logged in users only on a post?
Anyone know how to use ACF and show custom fields for logged in users only on a post?
Update: I think conditional formatting is what im after?
Any help much appreciated. | In the template you just need to check if the current user's logged in with `is_user_logged_in()`. Then output whatever HTML/PHP (including ACF functions) that you only want to show logged in users:
<?php if ( is_user_logged_in() ) : ?>
<!-- Output for only logged in users here. -->
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom field"
} |
The the post id from image id
Lets say I have the ID of an image. Is there a way that I get all the posts that have that image as their featured image? | The featured image is stored as post meta with the key `_thumbnail_id`, so you could use a meta query to get posts with a specific thumbnail:
$posts = new WP_Query( array(
'meta_query' => array(
array(
'key' => '_thumbnail_id',
'value' => $attachment_id,
),
),
) );
Where `$attachment_id` is the ID of the image. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.