qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
237,305 | <p><a href="https://i.stack.imgur.com/dWB4c.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dWB4c.jpg" alt="enter image description here"></a></p>
<p>I have been adding a post type to my theme, how do I hide/disable the Move to trash button?
Here is my code so far:</p>
<pre><code>$labels = array(
'name' => _x( 'Inhoud', 'taxonomy general name' ),
'singular_name' => _x( 'Inhoud', 'taxonomy singular name' ),
'search_items' => __( 'Zoek Inhoud' ),
// 'popular_items' => __( 'Popular Writers' ),
'all_items' => __( 'Alle Inhoud' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Wijzig Inhoud' ),
'update_item' => __( 'Update Inhoud' ),
'add_new_item' => __( 'Toevoegen Nieuwe Inhoud' ),
// 'new_item_name' => __( 'Nieuwe Evenement Naam' ),
// 'separate_items_with_commas' => __( 'Separate writers with commas' ),
// 'add_or_remove_items' => __( 'Add or remove writers' ),
// 'choose_from_most_used' => __( 'Choose from the most used writers' ),
'not_found' => __( 'Geen inhoud gevonden.' ),
'menu_name' => __( 'Inhoud' ),
);
$args = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
//'show_admin_column' => true,
//'update_count_callback' => '_update_post_term_count',
'menu_position' => 7,
'menu_icon' => 'dashicons-admin-post',
'show_in_menu' => true,
'show_in_nav_menus' => false,
'show_in_admin_bar' => false,
// 'query_var' => true,
// 'rewrite' => array( 'slug' => 'inhoud' ),
'capabilities' => array(
'create_posts' => 'do_not_allow',
//'edit_post' => 'true',
//'delete_posts' => 'do_not_allow'
),
'supports' => array( ),
'map_meta_cap' => array('delete_post' => false),
'has_archive' => true,
'public' => true
);
register_post_type( 'inhoud', $args );
</code></pre>
| [
{
"answer_id": 237306,
"author": "Bhagchandani",
"author_id": 101627,
"author_profile": "https://wordpress.stackexchange.com/users/101627",
"pm_score": 3,
"selected": true,
"text": "<p>You can hide move to trash button via adding css in the admin area. Try following code in <code>functio... | 2016/08/27 | [
"https://wordpress.stackexchange.com/questions/237305",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73800/"
] | [](https://i.stack.imgur.com/dWB4c.jpg)
I have been adding a post type to my theme, how do I hide/disable the Move to trash button?
Here is my code so far:
```
$labels = array(
'name' => _x( 'Inhoud', 'taxonomy general name' ),
'singular_name' => _x( 'Inhoud', 'taxonomy singular name' ),
'search_items' => __( 'Zoek Inhoud' ),
// 'popular_items' => __( 'Popular Writers' ),
'all_items' => __( 'Alle Inhoud' ),
'parent_item' => null,
'parent_item_colon' => null,
'edit_item' => __( 'Wijzig Inhoud' ),
'update_item' => __( 'Update Inhoud' ),
'add_new_item' => __( 'Toevoegen Nieuwe Inhoud' ),
// 'new_item_name' => __( 'Nieuwe Evenement Naam' ),
// 'separate_items_with_commas' => __( 'Separate writers with commas' ),
// 'add_or_remove_items' => __( 'Add or remove writers' ),
// 'choose_from_most_used' => __( 'Choose from the most used writers' ),
'not_found' => __( 'Geen inhoud gevonden.' ),
'menu_name' => __( 'Inhoud' ),
);
$args = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
//'show_admin_column' => true,
//'update_count_callback' => '_update_post_term_count',
'menu_position' => 7,
'menu_icon' => 'dashicons-admin-post',
'show_in_menu' => true,
'show_in_nav_menus' => false,
'show_in_admin_bar' => false,
// 'query_var' => true,
// 'rewrite' => array( 'slug' => 'inhoud' ),
'capabilities' => array(
'create_posts' => 'do_not_allow',
//'edit_post' => 'true',
//'delete_posts' => 'do_not_allow'
),
'supports' => array( ),
'map_meta_cap' => array('delete_post' => false),
'has_archive' => true,
'public' => true
);
register_post_type( 'inhoud', $args );
``` | You can hide move to trash button via adding css in the admin area. Try following code in `functions.php` file:
```
function my_custom_admin_styles() {
?>
<style type="text/css">
.post-type-inhoud form #delete-action{
display:none;
}
</style>
<?php
}
add_action('admin_head', 'my_custom_admin_styles');
``` |
237,327 | <p>I want to create shortcode like [genre] for WordPress. </p>
<pre><code>add_action( 'init', 'cptui_register_my_cpts_movie' );
function cptui_register_my_cpts_movie() {
$labels = array(
"name" => __( 'MOVIE', '' ),
"singular_name" => __( 'Movie', '' ),
"menu_name" => __( 'MOVIES LIBRARY', '' ),
"all_items" => __( 'All Movies', '' ),
"add_new" => __( 'Add New Movie', '' ),
"add_new_item" => __( 'Add New Movie', '' ),
"edit" => __( 'Edit', '' ),
"edit_item" => __( 'Edit Movie', '' ),
"new_item" => __( 'New Movie', '' ),
"view" => __( 'View', '' ),
"view_item" => __( 'View Movie', '' ),
"search_items" => __( 'Search Movie', '' ),
"not_found" => __( 'No Movies found', '' ),
"not_found_in_trash" => __( 'No Movies found in Trash', '' ),
"parent_item_colon" => __( 'Parent Movie', '' ),
);
$args = array(
"label" => __( 'MOVIE', '' ),
"labels" => $labels,
"description" => "All Publish Tools for Movies",
"public" => true,
"publicly_queryable" => false,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "movie", "with_front" => true ),
"query_var" => true,
"supports" => array( "title", "editor", "comments", "revisions", "thumbnail" ),
"taxonomies" => array( "genre", "year", "quality", "country", "awards", "type", "stars", "subtitle" ),
);
register_post_type( "movie", $args );
// End of cptui_register_my_cpts_movie()
}
</code></pre>
<p>I want to show 'genre' in shortcode</p>
<pre><code>function shortcode_for_genre() {
ob_start();
the_terms( $post->ID, array( 'taxonomy' => 'genre',), '', ', ', ' ' );
return ob_get_clean();
}
add_shortcode ('genre', 'shortcode_for_genre');
</code></pre>
<p>I'm tried above code and few other but no one works. This shortcode show genre of post. like drama, action. etc.</p>
| [
{
"answer_id": 237333,
"author": "wpclevel",
"author_id": 92212,
"author_profile": "https://wordpress.stackexchange.com/users/92212",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>page</code> post type.</p>\n\n<ul>\n<li>Simple to use.</li>\n<li>Easy to edit with page-bu... | 2016/08/28 | [
"https://wordpress.stackexchange.com/questions/237327",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101774/"
] | I want to create shortcode like [genre] for WordPress.
```
add_action( 'init', 'cptui_register_my_cpts_movie' );
function cptui_register_my_cpts_movie() {
$labels = array(
"name" => __( 'MOVIE', '' ),
"singular_name" => __( 'Movie', '' ),
"menu_name" => __( 'MOVIES LIBRARY', '' ),
"all_items" => __( 'All Movies', '' ),
"add_new" => __( 'Add New Movie', '' ),
"add_new_item" => __( 'Add New Movie', '' ),
"edit" => __( 'Edit', '' ),
"edit_item" => __( 'Edit Movie', '' ),
"new_item" => __( 'New Movie', '' ),
"view" => __( 'View', '' ),
"view_item" => __( 'View Movie', '' ),
"search_items" => __( 'Search Movie', '' ),
"not_found" => __( 'No Movies found', '' ),
"not_found_in_trash" => __( 'No Movies found in Trash', '' ),
"parent_item_colon" => __( 'Parent Movie', '' ),
);
$args = array(
"label" => __( 'MOVIE', '' ),
"labels" => $labels,
"description" => "All Publish Tools for Movies",
"public" => true,
"publicly_queryable" => false,
"show_ui" => true,
"show_in_rest" => false,
"rest_base" => "",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "movie", "with_front" => true ),
"query_var" => true,
"supports" => array( "title", "editor", "comments", "revisions", "thumbnail" ),
"taxonomies" => array( "genre", "year", "quality", "country", "awards", "type", "stars", "subtitle" ),
);
register_post_type( "movie", $args );
// End of cptui_register_my_cpts_movie()
}
```
I want to show 'genre' in shortcode
```
function shortcode_for_genre() {
ob_start();
the_terms( $post->ID, array( 'taxonomy' => 'genre',), '', ', ', ' ' );
return ob_get_clean();
}
add_shortcode ('genre', 'shortcode_for_genre');
```
I'm tried above code and few other but no one works. This shortcode show genre of post. like drama, action. etc. | I would not use WordPress pages nor articles for this.
Simply, create a new custom post type called "Projects", with a plugin like Types, then create a new custom taxonomy "Partners" and associate it with that custom post type.
Clean and easy structure. |
237,352 | <p>I want to make custom button for some products in place of add to cart button on shop page and set dynamic relinking to some other page. So I made a checkbox at the product page and if that checkbox is enabled then the custom button with different link will be visible to that product. here is the code for checkbox:</p>
<pre><code>add_action( 'add_meta_boxes', 'wdm_add_meta_box' );
add_action( 'add_meta_boxes', 'wdm_add_customize_enable_metabox' );
function wdm_add_customize_enable_metabox() {
add_meta_box(
'Checkbox_metabox',
'Check if you want to enable customization button',
'wdm_enable_callback',
'product',
'normal',
'high'
);
}
function wdm_enable_callback( $product ) {
$custom = get_post_custom( $product -> ID );
if( isset($custom[ "_wcm_custom_design_checkbox" ][0] ) ) {
$meta_box_check = $custom[ "_wcm_custom_design_checkbox" ][0];
}
else {
$meta_box_check = FALSE;
}
?>
<tr>
<td>Enable design panel at frontend?</td>
<td><input type="checkbox" name="wcm_enable_checkbox" id="wcm_enable_checkbox" <?php if ( $meta_box_check == true ) { ?> checked="checked"<?php } ?> /></td>
</tr>
<tr>
<?php
}
add_action( 'save_post', 'wdm_save_meta_check_box_data', 10,2 );
function wdm_save_meta_check_box_data( $post_id, $product ){
if ( $product -> post_type == 'product' ) {
if ( isset($_POST["wcm_enable_checkbox"] ) && $_POST["wcm_enable_checkbox"] ) {
update_post_meta( $post_id, '_wcm_custom_design_checkbox', $_POST["wcm_enable_checkbox"] );
}
else {
update_post_meta( $post_id, '_wcm_custom_design_checkbox', '');
}
}
}
</code></pre>
<p>The above code is working fine. I used this code into theme <code>add_to_cart</code> loop and here my only problem is how to get custom <code>add_to_cart_url()</code> for custom links and how to change the <code>add_to_cart_text()</code> text to whatever I want.</p>
<p>Here are the changes I made to <code>add_to_cart.php</code>:</p>
<pre><code>global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),//Here i want my own urls
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',//own css for custom text to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
</code></pre>
| [
{
"answer_id": 237370,
"author": "Ashish Pariyani",
"author_id": 101657,
"author_profile": "https://wordpress.stackexchange.com/users/101657",
"pm_score": -1,
"selected": false,
"text": "<p>Got it to work with just changing \"add_to_cart_url()\" to \"get_permalink()\" inside if statement... | 2016/08/28 | [
"https://wordpress.stackexchange.com/questions/237352",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101657/"
] | I want to make custom button for some products in place of add to cart button on shop page and set dynamic relinking to some other page. So I made a checkbox at the product page and if that checkbox is enabled then the custom button with different link will be visible to that product. here is the code for checkbox:
```
add_action( 'add_meta_boxes', 'wdm_add_meta_box' );
add_action( 'add_meta_boxes', 'wdm_add_customize_enable_metabox' );
function wdm_add_customize_enable_metabox() {
add_meta_box(
'Checkbox_metabox',
'Check if you want to enable customization button',
'wdm_enable_callback',
'product',
'normal',
'high'
);
}
function wdm_enable_callback( $product ) {
$custom = get_post_custom( $product -> ID );
if( isset($custom[ "_wcm_custom_design_checkbox" ][0] ) ) {
$meta_box_check = $custom[ "_wcm_custom_design_checkbox" ][0];
}
else {
$meta_box_check = FALSE;
}
?>
<tr>
<td>Enable design panel at frontend?</td>
<td><input type="checkbox" name="wcm_enable_checkbox" id="wcm_enable_checkbox" <?php if ( $meta_box_check == true ) { ?> checked="checked"<?php } ?> /></td>
</tr>
<tr>
<?php
}
add_action( 'save_post', 'wdm_save_meta_check_box_data', 10,2 );
function wdm_save_meta_check_box_data( $post_id, $product ){
if ( $product -> post_type == 'product' ) {
if ( isset($_POST["wcm_enable_checkbox"] ) && $_POST["wcm_enable_checkbox"] ) {
update_post_meta( $post_id, '_wcm_custom_design_checkbox', $_POST["wcm_enable_checkbox"] );
}
else {
update_post_meta( $post_id, '_wcm_custom_design_checkbox', '');
}
}
}
```
The above code is working fine. I used this code into theme `add_to_cart` loop and here my only problem is how to get custom `add_to_cart_url()` for custom links and how to change the `add_to_cart_text()` text to whatever I want.
Here are the changes I made to `add_to_cart.php`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),//Here i want my own urls
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',//own css for custom text to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
``` | Per [Ashish's](https://wordpress.stackexchange.com/users/101657/ashish-pariyani) answer that's been posted, below is the update code for clarification with the correct answer by switching `add_to_cart_url()` to `get_permalink()`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> get_permalink() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
``` |
237,365 | <p>I want to add an <code>id="myid"</code> to shortcode embedded iframe:-</p>
<pre><code>$video_url = get_post_meta($post_id, 'video_url',true);
//or
$video_url .= 'video url';
$check_embeds=$GLOBALS['wp_embed']->run_shortcode( '[embed]'. $video_url .'[/embed]' );
echo $check_embeds;
</code></pre>
<p>This code helps me to display video through custom meta box just using a video url. And additionally I want add an ID to iframe here, example:- <code><iframe id="myid" src=""></iframe></code>like this.
Can anybody help me to fix the issue?</p>
| [
{
"answer_id": 237370,
"author": "Ashish Pariyani",
"author_id": 101657,
"author_profile": "https://wordpress.stackexchange.com/users/101657",
"pm_score": -1,
"selected": false,
"text": "<p>Got it to work with just changing \"add_to_cart_url()\" to \"get_permalink()\" inside if statement... | 2016/08/28 | [
"https://wordpress.stackexchange.com/questions/237365",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101698/"
] | I want to add an `id="myid"` to shortcode embedded iframe:-
```
$video_url = get_post_meta($post_id, 'video_url',true);
//or
$video_url .= 'video url';
$check_embeds=$GLOBALS['wp_embed']->run_shortcode( '[embed]'. $video_url .'[/embed]' );
echo $check_embeds;
```
This code helps me to display video through custom meta box just using a video url. And additionally I want add an ID to iframe here, example:- `<iframe id="myid" src=""></iframe>`like this.
Can anybody help me to fix the issue? | Per [Ashish's](https://wordpress.stackexchange.com/users/101657/ashish-pariyani) answer that's been posted, below is the update code for clarification with the correct answer by switching `add_to_cart_url()` to `get_permalink()`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> get_permalink() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
``` |
237,368 | <p><a href="https://danscartoons.com" rel="nofollow noreferrer"><strong>My index page</strong></a> has three button on top upper right corner. They are Facebook, Twitter and RSS.</p>
<p>I have accessed my <code>header.php</code> to add the appropriate URL's for both Facebook & Twitter (I did not add RSS feed as of yet) below is a screenshot of what I have so far:</p>
<p><a href="https://i.stack.imgur.com/2BMUx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2BMUx.jpg" alt="screenshot"></a></p>
<p>However, the icons aren't going to the appropriate URL, why is that?</p>
| [
{
"answer_id": 237370,
"author": "Ashish Pariyani",
"author_id": 101657,
"author_profile": "https://wordpress.stackexchange.com/users/101657",
"pm_score": -1,
"selected": false,
"text": "<p>Got it to work with just changing \"add_to_cart_url()\" to \"get_permalink()\" inside if statement... | 2016/08/28 | [
"https://wordpress.stackexchange.com/questions/237368",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99226/"
] | [**My index page**](https://danscartoons.com) has three button on top upper right corner. They are Facebook, Twitter and RSS.
I have accessed my `header.php` to add the appropriate URL's for both Facebook & Twitter (I did not add RSS feed as of yet) below is a screenshot of what I have so far:
[](https://i.stack.imgur.com/2BMUx.jpg)
However, the icons aren't going to the appropriate URL, why is that? | Per [Ashish's](https://wordpress.stackexchange.com/users/101657/ashish-pariyani) answer that's been posted, below is the update code for clarification with the correct answer by switching `add_to_cart_url()` to `get_permalink()`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> get_permalink() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
``` |
237,374 | <p>Is there any neat way of disabling the figures/images in a certain post category until a user logs in. I want the entire post content to be visible except for the images.</p>
<p>I'm not a programmer and I have not found any useful plugin.</p>
| [
{
"answer_id": 237370,
"author": "Ashish Pariyani",
"author_id": 101657,
"author_profile": "https://wordpress.stackexchange.com/users/101657",
"pm_score": -1,
"selected": false,
"text": "<p>Got it to work with just changing \"add_to_cart_url()\" to \"get_permalink()\" inside if statement... | 2016/08/28 | [
"https://wordpress.stackexchange.com/questions/237374",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101304/"
] | Is there any neat way of disabling the figures/images in a certain post category until a user logs in. I want the entire post content to be visible except for the images.
I'm not a programmer and I have not found any useful plugin. | Per [Ashish's](https://wordpress.stackexchange.com/users/101657/ashish-pariyani) answer that's been posted, below is the update code for clarification with the correct answer by switching `add_to_cart_url()` to `get_permalink()`:
```
global $product, $post;
$hasCustomization = get_post_meta( $post -> ID, '_wcm_custom_design_checkbox', true );
if ( $hasCustomization == 'on' ) {
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> get_permalink() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? '' : '',to show
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )// Custom Text
),
$product
);
}
else{
echo apply_filters(
'woocommerce_loop_add_to_cart_link',
sprintf(
'<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="add_to_cart %s product_type_%s">%s</a>',
esc_url( $product -> add_to_cart_url() ),
esc_attr( $product -> id ),
esc_attr( $product -> get_sku() ),
$product -> is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product -> product_type ),
esc_html( $product -> add_to_cart_text() )
),
$product
);
}
?>
``` |
237,381 | <p>Suppose we registered the <code>composers</code> and the <code>interprets</code> custom taxonomies.</p>
<p>The <code>composers</code> taxonomy could have the following terms:</p>
<ul>
<li>Wolfgang Amadeus Mozart</li>
<li>Ludwig van Beethoven</li>
<li>Richard Wagner</li>
</ul>
<p>The <code>interprets</code> taxonomy could have the following terms:</p>
<ul>
<li>Glenn Gould</li>
<li>Daniel Barenboim</li>
<li>Vienna State Opera</li>
</ul>
<p>I am wondering whether the WordPress template hierarchy has a special file , like <code>taxonomy-terms.php</code>, to list taxonomy terms with a simple loop:</p>
<pre><code><?php
while ( have_posts() ) : the_post();
the_title();
endwhile;
?>
</code></pre>
<p>This would print (assuming the <code>/%postname%/</code> permalink setting): </p>
<ul>
<li><code>Wolfgang Amadeus Mozart</code>, <code>Ludwig van Beethoven</code>, <code>Richard Wagner</code> when viewing <code>example.com/composers</code></li>
<li><code>Glenn Gould</code>, <code>Daniel Barenboim</code>, <code>Vienna State Opera</code> when viewing <code>example.com/interprets</code></li>
</ul>
<p>If not, I would like to know the best way to implement this. I would create a page template for each taxonomy, <code>template-composers-terms.php</code> and <code>template-interprets-terms.php</code> and list terms using something like the following code:</p>
<pre><code><?php
/* Template Name: List of composers */ // or 'List of interprets'
$terms = get_terms( 'composers' ); // or get_terms( 'interprets' )
foreach ( $terms as $term ) :
echo $term->name;
endforeach;
?>
</code></pre>
<p>Then, I create two pages, "Composers" and "Interprets", to which I respectively assigned the "List of composers" and "List of interprets" templates.</p>
<p>I'm not very comfortable using this method, because it requires creating a new file for each taxonomy.</p>
| [
{
"answer_id": 237379,
"author": "markratledge",
"author_id": 268,
"author_profile": "https://wordpress.stackexchange.com/users/268",
"pm_score": 3,
"selected": true,
"text": "<p>PHP errors are the cause of whitescreens. You will have error logs in your Cpanel at Hostgator, but it's much... | 2016/08/28 | [
"https://wordpress.stackexchange.com/questions/237381",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88041/"
] | Suppose we registered the `composers` and the `interprets` custom taxonomies.
The `composers` taxonomy could have the following terms:
* Wolfgang Amadeus Mozart
* Ludwig van Beethoven
* Richard Wagner
The `interprets` taxonomy could have the following terms:
* Glenn Gould
* Daniel Barenboim
* Vienna State Opera
I am wondering whether the WordPress template hierarchy has a special file , like `taxonomy-terms.php`, to list taxonomy terms with a simple loop:
```
<?php
while ( have_posts() ) : the_post();
the_title();
endwhile;
?>
```
This would print (assuming the `/%postname%/` permalink setting):
* `Wolfgang Amadeus Mozart`, `Ludwig van Beethoven`, `Richard Wagner` when viewing `example.com/composers`
* `Glenn Gould`, `Daniel Barenboim`, `Vienna State Opera` when viewing `example.com/interprets`
If not, I would like to know the best way to implement this. I would create a page template for each taxonomy, `template-composers-terms.php` and `template-interprets-terms.php` and list terms using something like the following code:
```
<?php
/* Template Name: List of composers */ // or 'List of interprets'
$terms = get_terms( 'composers' ); // or get_terms( 'interprets' )
foreach ( $terms as $term ) :
echo $term->name;
endforeach;
?>
```
Then, I create two pages, "Composers" and "Interprets", to which I respectively assigned the "List of composers" and "List of interprets" templates.
I'm not very comfortable using this method, because it requires creating a new file for each taxonomy. | PHP errors are the cause of whitescreens. You will have error logs in your Cpanel at Hostgator, but it's much easier to use the debug logs that are available in WordPress. *(For debugging outside of the WordPress environment, see <http://php.net/manual/en/debugger-about.php> about PHP's own debugger and third-party debuggers).*
And, there are several other debugging methods you should learn when working with WordPress - in order to handle PHP as well as to debug database queries and find/fix Javascript errors - since WordPress (and themes and plugins) use a database as well as Javascript.
**PHP**
For PHP debugging and finding the , use the built-in WordPress function `WP_DEBUG`. See <https://codex.wordpress.org/WP_DEBUG>
Add
`define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );`
in wp-config.php and the debug.log file will be in wp-content.
Add this line
`define( 'WP_DEBUG_DISPLAY', true);`
to wp-config.php to log *and* dump them to the browser.
*See this answer to find out how to change the location of the `debug.log` file: [Is it possible to change the log file location for WP\_DEBUG\_LOG?](https://wordpress.stackexchange.com/questions/84132/is-it-possible-to-change-the-log-file-location-for-wp-debug-log)*
**Database queries:**
Also look at the plugins <https://wordpress.org/plugins/debug-objects/> and <https://wordpress.org/plugins/debug-bar/> for help with database queries.
You need to set
`define('SAVEQUERIES', true);`
in wp-config.php to debug database queries.
**Javascript:**
For Javascript, you can turn on
`define('SCRIPT_DEBUG', true);`
too, in wp-config.php.
And be sure and learn how to use the developer tools in [Firefox](https://developer.mozilla.org/en-US/docs/Tools) (or [Firebug](http://getfirebug.com/)) or [Chrome](https://developers.chrome.com/devtools/) or [Safari](https://developer.apple.com/safari/tools/) or [IE](http://msdn.microsoft.com/en-us/library/ie/hh673541(v=vs.85).aspx) to work with Javascript as well as HTML and CSS issues. |
237,385 | <p>so i wrote a simple script and enqueued it properly.</p>
<p><strong>my-jquery-script.js:</strong></p>
<pre><code>jQuery(document).ready(function($) {
$('#some_id').on('click','.clone',function(e){
alert('clicked');
/*.....*/
e.preventDefault();
});
});
</code></pre>
<p><strong>functions.php:</strong></p>
<pre><code>add_action( 'wp_enqueue_scripts', 'my_function' );
function my_function() {
wp_enqueue_script( 'my-jquery-script', get_stylesheet_directory_uri() . '/js/my-jquery-script.js' );
}
</code></pre>
<p><strong>some-page.php:</strong></p>
<pre><code><?php wp_head(); ?>
<body>
<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
</form>
</body>
<?php wp_footer(); ?>
</code></pre>
<p>it's not working but when i include jQuery script manually into <em>some-page.php</em> like this:</p>
<pre><code><?php wp_head(); ?>
<body>
<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
<script type='text/javascript' src='<?php echo get_stylesheet_directory_uri() . "/js/my-jquery-script.js"; ?>'></script>
</form>
</body>
<?php wp_footer(); ?>
</code></pre>
<p>it's working but "$(document).ready () fires twice" as mentioned here: <a href="https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice">https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice</a></p>
<p>What am i doing wrong? Any help would be appreciated.</p>
<p><em>update: I also noticed that <code>$(document.body).on('click','.clone',function(e){ }</code> selector is working instead of id selector.</em></p>
| [
{
"answer_id": 237387,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>If your script depends on jQuery, you have to declare that dependency to make sure WordPress will enqueue it earlier ... | 2016/08/28 | [
"https://wordpress.stackexchange.com/questions/237385",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101800/"
] | so i wrote a simple script and enqueued it properly.
**my-jquery-script.js:**
```
jQuery(document).ready(function($) {
$('#some_id').on('click','.clone',function(e){
alert('clicked');
/*.....*/
e.preventDefault();
});
});
```
**functions.php:**
```
add_action( 'wp_enqueue_scripts', 'my_function' );
function my_function() {
wp_enqueue_script( 'my-jquery-script', get_stylesheet_directory_uri() . '/js/my-jquery-script.js' );
}
```
**some-page.php:**
```
<?php wp_head(); ?>
<body>
<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
</form>
</body>
<?php wp_footer(); ?>
```
it's not working but when i include jQuery script manually into *some-page.php* like this:
```
<?php wp_head(); ?>
<body>
<form>
<div id="some_id">
<a href="#" class="clone">button</a>
</div>
<script type='text/javascript' src='<?php echo get_stylesheet_directory_uri() . "/js/my-jquery-script.js"; ?>'></script>
</form>
</body>
<?php wp_footer(); ?>
```
it's working but "$(document).ready () fires twice" as mentioned here: <https://stackoverflow.com/questions/10727002/jquery-document-ready-fires-twice>
What am i doing wrong? Any help would be appreciated.
*update: I also noticed that `$(document.body).on('click','.clone',function(e){ }` selector is working instead of id selector.* | If your script depends on jQuery, you have to declare that dependency to make sure WordPress will enqueue it earlier than yours.
```
wp_enqueue_script(
'my-jquery-script',
get_stylesheet_directory_uri() . '/js/my-jquery-script.js',
[ 'jquery' ] /* declare the dependency */
);
``` |
237,395 | <p>I've been using site/page builders for so long in WP that I'm OOTL with the current setup of templates, stylesheets and functions in the newer WP builds.</p>
<p>I've got an older theme that I need to make a unique page for and am struggling to understand how to use a specific stylesheet for this page template.
If the page template is referral.php and I've added the header and footer into the template (so that I can use unique elements compared to the main site), I can see that the header brings in the sytlesheet using <code><?php wp_head(); ?></code>.</p>
<p><strong>What's the best way for this page to use the majority of the parent and child theme styles, but process my specific unique styles for this page ONLY?</strong></p>
<p>Is it to use <code><link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_uri(); ?>/referral-style.css"></code> or is it to create a functions file in the child theme directory and use something like:</p>
<pre><code><?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) {
exit;
}
?>
<?php
function themeslug_enqueue_style() {
if( is_page( 'referral' ) ) { // Only add this style onto the Blog page.
wp_enqueue_style( 'referral-style', get_stylesheet_uri() );
}
if ( is_child_theme() ) {
// load parent stylesheet first if this is a child theme
wp_enqueue_style( 'parent-stylesheet', trailingslashit( get_template_directory_uri() ) . 'style.css', false );
}
// load active theme stylesheet in both cases
wp_enqueue_style( 'theme-stylesheet', get_stylesheet_uri(), false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
</code></pre>
| [
{
"answer_id": 237398,
"author": "CodeMascot",
"author_id": 44192,
"author_profile": "https://wordpress.stackexchange.com/users/44192",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't need to use often some scripts or styles, it's better to register them before <code>enqueue</... | 2016/08/29 | [
"https://wordpress.stackexchange.com/questions/237395",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30889/"
] | I've been using site/page builders for so long in WP that I'm OOTL with the current setup of templates, stylesheets and functions in the newer WP builds.
I've got an older theme that I need to make a unique page for and am struggling to understand how to use a specific stylesheet for this page template.
If the page template is referral.php and I've added the header and footer into the template (so that I can use unique elements compared to the main site), I can see that the header brings in the sytlesheet using `<?php wp_head(); ?>`.
**What's the best way for this page to use the majority of the parent and child theme styles, but process my specific unique styles for this page ONLY?**
Is it to use `<link rel="stylesheet" type="text/css" href="<?php echo get_stylesheet_uri(); ?>/referral-style.css">` or is it to create a functions file in the child theme directory and use something like:
```
<?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) {
exit;
}
?>
<?php
function themeslug_enqueue_style() {
if( is_page( 'referral' ) ) { // Only add this style onto the Blog page.
wp_enqueue_style( 'referral-style', get_stylesheet_uri() );
}
if ( is_child_theme() ) {
// load parent stylesheet first if this is a child theme
wp_enqueue_style( 'parent-stylesheet', trailingslashit( get_template_directory_uri() ) . 'style.css', false );
}
// load active theme stylesheet in both cases
wp_enqueue_style( 'theme-stylesheet', get_stylesheet_uri(), false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
``` | The preferred way is to use `add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );` within your child theme `functions.php` file or directly in your `referral.php` template page. Either way, it's by using `add_action` and not by echoing into the `<link>` tag.
Registering your style is also a recommended practice. The one benefit I would see in your case is that you could register all your styles in your `functions.php` with for each file their dependencies, then you would have to enqueue only one handle in your referral page and WP would load all other files registered as dependencies of your `referral-style.css`.
For instance, in `functions.php`
```
function themeslug_enqueue_style() {
wp_register_style( 'referral-style', get_stylesheet_directory_uri() . 'path/to/your/css-file', array( 'theme-stylesheet' ) );
wp_register_style( 'theme-stylesheet', get_stylesheet_uri() );
// load active theme stylesheet in all cases
wp_enqueue_style( 'theme-stylesheet' );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
```
and in `referral.php`
```
function my_referral_enqueue_style() {
wp_enqueue_style( 'referral-style' ); // will load theme-stylesheet automatically
}
add_action( 'wp_enqueue_scripts', 'my_referral_enqueue_style' );
```
of course you can omit this in `referral.php` and still add a conditional in your `functions.php`
```
if( is_page( 'referral' ) ) {
wp_enqueue_style( 'referral-style' );
}
```
But I wanted to show you both ways |
237,410 | <p>I'm new to WordPress, and I'm having an issue with "The Loop."
I have 2 custom post type named 'book' and 'author'
.in author post type I have custom filed checkbox which can choose between author and translator.
also in book post type I have 2 metaboxs which user must choose the name of author and translator from those.
all metabox and custom post type work well but when I want to call them and use the values of each meta-box I have problem.
my code can read author values well, but translator values just show the last value of author and I cant' figure out why this happen ?
I think foreach is the problem. but I don't know how can I solve it.
here is my code for single-book.php</p>
<pre><code><?php $args = array( 'post_type' => 'book');
$loop = new WP_Query( $args );
while ( have_posts() ) : the_post();
// for reading author which choose from cheak box in each book pages.
$post_id = get_the_ID();
$key = 'save-author-to-book';
$key2='save-trans-to-book';
$vals=get_post_meta($post_id, $key2, true);
$values = get_post_meta( $post_id, $key, true );
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
echo '<h4 class="text-right color-style"> نویسنده : ';
foreach($values as $value){
$author=get_post($value);
echo '<a href="'.
get_post_permalink($value).'" target="_blank">'.
$author->post_title .'</a> ، ' ;}
echo '</h4>';
echo '<h4 class="text-right color-style"> مترجم : ';
foreach($vals as $val){
$trans=get_post($val);
echo '<a href="'.
get_post_permalink($val).'" target="_blank">'.
$author->post_title.'</a>، ';}
echo '</h4>';
</code></pre>
<p>any idea would be appreciated. </p>
| [
{
"answer_id": 237414,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 2,
"selected": true,
"text": "<p>I believe your issue is with <code>$vals=get_post_meta($post_id, $key2, true);</code></p>\n\n<p>If you check... | 2016/08/29 | [
"https://wordpress.stackexchange.com/questions/237410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101035/"
] | I'm new to WordPress, and I'm having an issue with "The Loop."
I have 2 custom post type named 'book' and 'author'
.in author post type I have custom filed checkbox which can choose between author and translator.
also in book post type I have 2 metaboxs which user must choose the name of author and translator from those.
all metabox and custom post type work well but when I want to call them and use the values of each meta-box I have problem.
my code can read author values well, but translator values just show the last value of author and I cant' figure out why this happen ?
I think foreach is the problem. but I don't know how can I solve it.
here is my code for single-book.php
```
<?php $args = array( 'post_type' => 'book');
$loop = new WP_Query( $args );
while ( have_posts() ) : the_post();
// for reading author which choose from cheak box in each book pages.
$post_id = get_the_ID();
$key = 'save-author-to-book';
$key2='save-trans-to-book';
$vals=get_post_meta($post_id, $key2, true);
$values = get_post_meta( $post_id, $key, true );
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
?>
echo '<h4 class="text-right color-style"> نویسنده : ';
foreach($values as $value){
$author=get_post($value);
echo '<a href="'.
get_post_permalink($value).'" target="_blank">'.
$author->post_title .'</a> ، ' ;}
echo '</h4>';
echo '<h4 class="text-right color-style"> مترجم : ';
foreach($vals as $val){
$trans=get_post($val);
echo '<a href="'.
get_post_permalink($val).'" target="_blank">'.
$author->post_title.'</a>، ';}
echo '</h4>';
```
any idea would be appreciated. | I believe your issue is with `$vals=get_post_meta($post_id, $key2, true);`
If you check the codex, the last parameter for [get\_post\_meta](https://developer.wordpress.org/reference/functions/get_post_meta/) is whether to return a single value or array of values. You have set it to `true` which means return only one value.
Try it with `false` (the default) it should work. |
237,427 | <p>After getting so close to nailing my theme I've hit the last hurdle. Essentially I have three different areas on my homepage:</p>
<ol>
<li>The latest post appears in the header and styled as a featured post</li>
<li>Two posts below that styled as recent posts</li>
<li>The rest of the posts (10) in date order below those</li>
</ol>
<p>Latest post (1) and the two recent posts (2) are shown using a custom WP_Query and the remaining ten posts (3) are shown using the standard loop with an offset function which also solves the pagination BUT... there's a hiccup with page 2. For some reason, it's adding an extra three posts to the top of the list of posts (3)? After this, page 3 onwards, it's fine and works as it should. I should also mention that the latest and recent posts (1 and 2) are to be shown at the top at all times as you cycle through the pages.</p>
<p>Here the layout with the different areas and post numbers:</p>
<p><a href="https://i.stack.imgur.com/xXxdz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xXxdz.png" alt="Layout"></a></p>
<p>Here's the code used for the function that handles the main posts (3) and the pagination fix (the offset is used to skip the latest and recent posts shown above these):</p>
<pre><code>function offset_main_query ( $query ) {
if ( $query->is_home() && $query->is_main_query() && !$query->is_paged() ) {
$query->set( 'offset', '3' );
}
}
add_action( 'pre_get_posts', 'offset_main_query' );
</code></pre>
<p>Any help would be great as this is the last bit that's tripping me up.</p>
<p>Thanks :)</p>
| [
{
"answer_id": 237444,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 0,
"selected": false,
"text": "<p>I would probably try without the <code>&& !$query->is_paged()</code> (you already have 2 conditions... | 2016/08/29 | [
"https://wordpress.stackexchange.com/questions/237427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99335/"
] | After getting so close to nailing my theme I've hit the last hurdle. Essentially I have three different areas on my homepage:
1. The latest post appears in the header and styled as a featured post
2. Two posts below that styled as recent posts
3. The rest of the posts (10) in date order below those
Latest post (1) and the two recent posts (2) are shown using a custom WP\_Query and the remaining ten posts (3) are shown using the standard loop with an offset function which also solves the pagination BUT... there's a hiccup with page 2. For some reason, it's adding an extra three posts to the top of the list of posts (3)? After this, page 3 onwards, it's fine and works as it should. I should also mention that the latest and recent posts (1 and 2) are to be shown at the top at all times as you cycle through the pages.
Here the layout with the different areas and post numbers:
[](https://i.stack.imgur.com/xXxdz.png)
Here's the code used for the function that handles the main posts (3) and the pagination fix (the offset is used to skip the latest and recent posts shown above these):
```
function offset_main_query ( $query ) {
if ( $query->is_home() && $query->is_main_query() && !$query->is_paged() ) {
$query->set( 'offset', '3' );
}
}
add_action( 'pre_get_posts', 'offset_main_query' );
```
Any help would be great as this is the last bit that's tripping me up.
Thanks :) | Here's a suggestion for a general way to support **different** number of posts on the *home page* than on the *other paginated pages*. We should use the *main query* instead of *sub-queries*, if possible.
**Formula**
It seems to make sense to take the *offset* for paginated pages as:
```
offset_op = ( paged - 1 ) * pp_op + ( pp_fp - pp_op ) + offset_fp
= ( paged - 2 ) * pp_op + pp_fp + offset_fp
```
where `paged` (*pagination*), `pp_fp` (*posts per first page*), `pp_op` (*posts per other pages*) and offset\_fp (*offset for the first page*) are non-negative integers.
For `paged=1` the offset is `offset_fp`, else it's `offset_op` for other pages.
**Example #1:**
First we calculate the offset for few pages to better understand this:
```
For paged=1:
offset_fp = 0
For paged=2:
offset_op = (2-2)*10 + 13 + 0
= 13
For paged=3:
offset_op = (3-2)*10 + 13 + 0
= 10+13
= 23
...
```
Here's a list of post indices on each page:
```
0,1,2,3,4,5,6,7,8,9,10,11,12 (offset_fp=0, pp_fp=13, paged=1)
13,14,15,16,17,18,19,20,21,22 (offset_op=13, pp_op=10, paged=2)
23,24,25,26, 27,28,29,30,31,32 (offset_op=23, pp_op=10, paged=3)
...
```
We can see that the offset matches the indices.
**Example #2:**
Let's take `pp_fp = 3`, `pp_op = 5`, `offset_fp=4` and calculate the *offset\_op*:
```
For paged=1:
offset_fp = 4
For paged=2:
offset_op = (2-2)*5 + 3 + 4
= 7
For paged=3:
offset_op = (3-2)*5 + 3 + 4
= 5+3+4
= 12
...
```
and compare it to the indices:
```
4,5,6 (offset_fp=4, pp_fp=3, paged=1)
7,8,9,10,11 (offset_op=7, pp_op=5, paged=2)
12,13,14,15,16 (offset_op=12, pp_op=5, paged=3)
...
```
**Demo Plugin**
Here's a demo implementation:
```
/**
* Plugin Name: WPSE demo
*/
add_action( 'pre_get_posts', function( \WP_Query $query )
{
// Nothing to do if backend or not home page or not the main query
if ( is_admin() || ! $query->is_home() || ! $query->is_main_query() )
return;
// Get current pagination
$paged = get_query_var( 'paged', 1 );
// Modify sticky posts display
$query->set( 'ignore_sticky_posts', true );
// Modify post status
$query->set( 'post_status', 'publish' );
// Edit to your needs
$pp_fp = 13; // posts per first page
$pp_op = 10; // posts per other pages
$offset_fp = 0; // offset for the first page
// Offset for other pages than the first page
$offset_op = ( $paged - 2 ) * $pp_op + $pp_fp + $offset_fp;
// Modify offset
$query->set( 'offset', $query->is_paged() ? $offset_op : $offset_fp );
// Modify posts per page
$query->set( 'posts_per_page', $query->is_paged() ? $pp_op : $pp_fp );
} );
```
Hope you can adjust it to your needs! |
237,436 | <p>Can anyone tell me how to create a function out of the following code? It's for displaying page navigation links in a custom category template. As you can see, it's quite a large block of code and I would like to wrap it in a function so I can generate the links with just a single line of code in my template.</p>
<p>Here it is:</p>
<pre><code><?php
// Start of Pagination
$total_childs_query = get_categories( array( 'parent' => $cat_id, 'hide_empty' => '0' ));
$total_terms = count( $total_childs_query );
$pages = ceil($total_terms/$catnum);
$base_url = get_term_link( $cat_id, get_query_var( 'taxonomy' ) );
// if there's more than one page
if( $pages > 1 ):
echo '<div class="ft-paginate">';
echo '<nav class="navigation pagination" role="navigation">';
echo '<h2 class="screen-reader-text">Posts navigation</h2>';
echo '<div class="nav-links">';
// if we're not on the first page, print the previous-link
if ( $catpage > 1 ) {
$prevpage = $catpage - 1;
if ( $prevpage > 1 ) {
echo '<a class="prev page-numbers" href="' . $base_url . '/page/' . $prevpage . '"><i class="fa fa-angle-left"></i></a>';
}
else {
echo '<a class="prev page-numbers" href="' . $base_url . '"><i class="fa fa-angle-left"></i></a>';
}
}
for ($pagecount=1; $pagecount <= $pages; $pagecount++):
//set class
$class = "page-numbers";
if ( $pagecount == $catpage ) {
$class .= " current";
}
if ( $pagecount == $catpage ) {
echo '&nbsp;<span class="' . $class . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</span>';
}
else if ( $pagecount == 1 ) {
echo '&nbsp;<a class="' . $class . '" href="' . $base_url . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
else {
echo '&nbsp;<a class="' . $class . '" href="' . $base_url . '/page/' . $pagecount . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
endfor;
// if there is one more page after the current, print the next-link
if ( $catpage < $pages ) {
$nextpage = $catpage + 1;
echo '&nbsp;<a class="next' . $class . '" href="' . $base_url . '/page/' . $nextpage . '"><i class="fa fa-angle-right"></i></a>';
}
echo '</div>';
echo '</nav>';
printf( '<span class="total-pages">' . esc_html__( 'Page %1$s of %2$s', 'codilight-lite' ) . '</span>', $catpage, $pages );
echo '</div>';
endif;
// End of Pagination
?>
</code></pre>
<p>And here's the the custom category template with the above pagination code included:</p>
<pre><code><?php
/**
* Category Template: Custom
*/
get_header(); ?>
<div id="content" class="site-content container <?php echo codilight_lite_sidebar_position(); ?>">
<div class="content-inside">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
$catpage = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$catnum = 2;
$offset = ($catnum * $catpage) - 2;
$cat = get_category( get_query_var( 'cat' ) );
$cat_id = $cat->cat_ID;
$child_categories=get_categories(
array(
'parent' => $cat_id,
'orderby' => 'id',
'order' => 'DESC',
'hide_empty' => '0',
'number' => $catnum,
'offset' => $offset,
'paged' => $catpage
)
);
if (!empty($child_categories)) : $count = 0; ?>
<header class="page-header">
<?php
the_archive_title( '<h1 class="page-title">', '</h1>' );
the_archive_description( '<div class="taxonomy-description">', '</div>' );
?>
</header><!-- .page-header -->
<?php
echo '<div class="block1 block1_grid">';
echo '<div class="row">';
foreach ( $child_categories as $child ){ $count++;
include( locate_template( 'template-parts/content-custom.php' ) );
if ( $count % 2 == 0 ) {
echo '</div>';
echo '<div class="row">';
}
}
echo '</div>';
echo '</div>';
?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
<?php
// Start of Pagination
$total_childs_query = get_categories( array( 'parent' => $cat_id, 'hide_empty' => '0' ));
$total_terms = count( $total_childs_query );
$pages = ceil($total_terms/$catnum);
$base_url = get_term_link( $cat_id, get_query_var( 'taxonomy' ) );
// if there's more than one page
if( $pages > 1 ):
echo '<div class="ft-paginate">';
echo '<nav class="navigation pagination" role="navigation">';
echo '<h2 class="screen-reader-text">Posts navigation</h2>';
echo '<div class="nav-links">';
// if we're not on the first page, print the previous-link
if ( $catpage > 1 ) {
$prevpage = $catpage - 1;
if ( $prevpage > 1 ) {
echo '<a class="prev page-numbers" href="' . $base_url . '/page/' . $prevpage . '"><i class="fa fa-angle-left"></i></a>';
}
else {
echo '<a class="prev page-numbers" href="' . $base_url . '"><i class="fa fa-angle-left"></i></a>';
}
}
for ($pagecount=1; $pagecount <= $pages; $pagecount++):
//set class
$class = "page-numbers";
if ( $pagecount == $catpage ) {
$class .= " current";
}
if ( $pagecount == $catpage ) {
echo '&nbsp;<span class="' . $class . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</span>';
}
else if ( $pagecount == 1 ) {
echo '&nbsp;<a class="' . $class . '" href="' . $base_url . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
else {
echo '&nbsp;<a class="' . $class . '" href="' . $base_url . '/page/' . $pagecount . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
endfor;
// if there is one more page after the current, print the next-link
if ( $catpage < $pages ) {
$nextpage = $catpage + 1;
echo '&nbsp;<a class="next' . $class . '" href="' . $base_url . '/page/' . $nextpage . '"><i class="fa fa-angle-right"></i></a>';
}
echo '</div>';
echo '</nav>';
printf( '<span class="total-pages">' . esc_html__( 'Page %1$s of %2$s', 'codilight-lite' ) . '</span>', $catpage, $pages );
echo '</div>';
endif;
// End of Pagination
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 237444,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 0,
"selected": false,
"text": "<p>I would probably try without the <code>&& !$query->is_paged()</code> (you already have 2 conditions... | 2016/08/29 | [
"https://wordpress.stackexchange.com/questions/237436",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
] | Can anyone tell me how to create a function out of the following code? It's for displaying page navigation links in a custom category template. As you can see, it's quite a large block of code and I would like to wrap it in a function so I can generate the links with just a single line of code in my template.
Here it is:
```
<?php
// Start of Pagination
$total_childs_query = get_categories( array( 'parent' => $cat_id, 'hide_empty' => '0' ));
$total_terms = count( $total_childs_query );
$pages = ceil($total_terms/$catnum);
$base_url = get_term_link( $cat_id, get_query_var( 'taxonomy' ) );
// if there's more than one page
if( $pages > 1 ):
echo '<div class="ft-paginate">';
echo '<nav class="navigation pagination" role="navigation">';
echo '<h2 class="screen-reader-text">Posts navigation</h2>';
echo '<div class="nav-links">';
// if we're not on the first page, print the previous-link
if ( $catpage > 1 ) {
$prevpage = $catpage - 1;
if ( $prevpage > 1 ) {
echo '<a class="prev page-numbers" href="' . $base_url . '/page/' . $prevpage . '"><i class="fa fa-angle-left"></i></a>';
}
else {
echo '<a class="prev page-numbers" href="' . $base_url . '"><i class="fa fa-angle-left"></i></a>';
}
}
for ($pagecount=1; $pagecount <= $pages; $pagecount++):
//set class
$class = "page-numbers";
if ( $pagecount == $catpage ) {
$class .= " current";
}
if ( $pagecount == $catpage ) {
echo ' <span class="' . $class . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</span>';
}
else if ( $pagecount == 1 ) {
echo ' <a class="' . $class . '" href="' . $base_url . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
else {
echo ' <a class="' . $class . '" href="' . $base_url . '/page/' . $pagecount . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
endfor;
// if there is one more page after the current, print the next-link
if ( $catpage < $pages ) {
$nextpage = $catpage + 1;
echo ' <a class="next' . $class . '" href="' . $base_url . '/page/' . $nextpage . '"><i class="fa fa-angle-right"></i></a>';
}
echo '</div>';
echo '</nav>';
printf( '<span class="total-pages">' . esc_html__( 'Page %1$s of %2$s', 'codilight-lite' ) . '</span>', $catpage, $pages );
echo '</div>';
endif;
// End of Pagination
?>
```
And here's the the custom category template with the above pagination code included:
```
<?php
/**
* Category Template: Custom
*/
get_header(); ?>
<div id="content" class="site-content container <?php echo codilight_lite_sidebar_position(); ?>">
<div class="content-inside">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
$catpage = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$catnum = 2;
$offset = ($catnum * $catpage) - 2;
$cat = get_category( get_query_var( 'cat' ) );
$cat_id = $cat->cat_ID;
$child_categories=get_categories(
array(
'parent' => $cat_id,
'orderby' => 'id',
'order' => 'DESC',
'hide_empty' => '0',
'number' => $catnum,
'offset' => $offset,
'paged' => $catpage
)
);
if (!empty($child_categories)) : $count = 0; ?>
<header class="page-header">
<?php
the_archive_title( '<h1 class="page-title">', '</h1>' );
the_archive_description( '<div class="taxonomy-description">', '</div>' );
?>
</header><!-- .page-header -->
<?php
echo '<div class="block1 block1_grid">';
echo '<div class="row">';
foreach ( $child_categories as $child ){ $count++;
include( locate_template( 'template-parts/content-custom.php' ) );
if ( $count % 2 == 0 ) {
echo '</div>';
echo '<div class="row">';
}
}
echo '</div>';
echo '</div>';
?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
<?php
// Start of Pagination
$total_childs_query = get_categories( array( 'parent' => $cat_id, 'hide_empty' => '0' ));
$total_terms = count( $total_childs_query );
$pages = ceil($total_terms/$catnum);
$base_url = get_term_link( $cat_id, get_query_var( 'taxonomy' ) );
// if there's more than one page
if( $pages > 1 ):
echo '<div class="ft-paginate">';
echo '<nav class="navigation pagination" role="navigation">';
echo '<h2 class="screen-reader-text">Posts navigation</h2>';
echo '<div class="nav-links">';
// if we're not on the first page, print the previous-link
if ( $catpage > 1 ) {
$prevpage = $catpage - 1;
if ( $prevpage > 1 ) {
echo '<a class="prev page-numbers" href="' . $base_url . '/page/' . $prevpage . '"><i class="fa fa-angle-left"></i></a>';
}
else {
echo '<a class="prev page-numbers" href="' . $base_url . '"><i class="fa fa-angle-left"></i></a>';
}
}
for ($pagecount=1; $pagecount <= $pages; $pagecount++):
//set class
$class = "page-numbers";
if ( $pagecount == $catpage ) {
$class .= " current";
}
if ( $pagecount == $catpage ) {
echo ' <span class="' . $class . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</span>';
}
else if ( $pagecount == 1 ) {
echo ' <a class="' . $class . '" href="' . $base_url . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
else {
echo ' <a class="' . $class . '" href="' . $base_url . '/page/' . $pagecount . '"><span class="screen-reader-text">Page</span>' . $pagecount . '</a>';
}
endfor;
// if there is one more page after the current, print the next-link
if ( $catpage < $pages ) {
$nextpage = $catpage + 1;
echo ' <a class="next' . $class . '" href="' . $base_url . '/page/' . $nextpage . '"><i class="fa fa-angle-right"></i></a>';
}
echo '</div>';
echo '</nav>';
printf( '<span class="total-pages">' . esc_html__( 'Page %1$s of %2$s', 'codilight-lite' ) . '</span>', $catpage, $pages );
echo '</div>';
endif;
// End of Pagination
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
``` | Here's a suggestion for a general way to support **different** number of posts on the *home page* than on the *other paginated pages*. We should use the *main query* instead of *sub-queries*, if possible.
**Formula**
It seems to make sense to take the *offset* for paginated pages as:
```
offset_op = ( paged - 1 ) * pp_op + ( pp_fp - pp_op ) + offset_fp
= ( paged - 2 ) * pp_op + pp_fp + offset_fp
```
where `paged` (*pagination*), `pp_fp` (*posts per first page*), `pp_op` (*posts per other pages*) and offset\_fp (*offset for the first page*) are non-negative integers.
For `paged=1` the offset is `offset_fp`, else it's `offset_op` for other pages.
**Example #1:**
First we calculate the offset for few pages to better understand this:
```
For paged=1:
offset_fp = 0
For paged=2:
offset_op = (2-2)*10 + 13 + 0
= 13
For paged=3:
offset_op = (3-2)*10 + 13 + 0
= 10+13
= 23
...
```
Here's a list of post indices on each page:
```
0,1,2,3,4,5,6,7,8,9,10,11,12 (offset_fp=0, pp_fp=13, paged=1)
13,14,15,16,17,18,19,20,21,22 (offset_op=13, pp_op=10, paged=2)
23,24,25,26, 27,28,29,30,31,32 (offset_op=23, pp_op=10, paged=3)
...
```
We can see that the offset matches the indices.
**Example #2:**
Let's take `pp_fp = 3`, `pp_op = 5`, `offset_fp=4` and calculate the *offset\_op*:
```
For paged=1:
offset_fp = 4
For paged=2:
offset_op = (2-2)*5 + 3 + 4
= 7
For paged=3:
offset_op = (3-2)*5 + 3 + 4
= 5+3+4
= 12
...
```
and compare it to the indices:
```
4,5,6 (offset_fp=4, pp_fp=3, paged=1)
7,8,9,10,11 (offset_op=7, pp_op=5, paged=2)
12,13,14,15,16 (offset_op=12, pp_op=5, paged=3)
...
```
**Demo Plugin**
Here's a demo implementation:
```
/**
* Plugin Name: WPSE demo
*/
add_action( 'pre_get_posts', function( \WP_Query $query )
{
// Nothing to do if backend or not home page or not the main query
if ( is_admin() || ! $query->is_home() || ! $query->is_main_query() )
return;
// Get current pagination
$paged = get_query_var( 'paged', 1 );
// Modify sticky posts display
$query->set( 'ignore_sticky_posts', true );
// Modify post status
$query->set( 'post_status', 'publish' );
// Edit to your needs
$pp_fp = 13; // posts per first page
$pp_op = 10; // posts per other pages
$offset_fp = 0; // offset for the first page
// Offset for other pages than the first page
$offset_op = ( $paged - 2 ) * $pp_op + $pp_fp + $offset_fp;
// Modify offset
$query->set( 'offset', $query->is_paged() ? $offset_op : $offset_fp );
// Modify posts per page
$query->set( 'posts_per_page', $query->is_paged() ? $pp_op : $pp_fp );
} );
```
Hope you can adjust it to your needs! |
237,438 | <p>I'm trying to give custom color to each <strong>category item</strong>, But it gives only one style to all items.</p>
<p>I use this plugin for the colors:
'<a href="https://wordpress.org/plugins/category-color/" rel="nofollow">Category Color</a>'</p>
<p>My code as below,</p>
<pre><code><?php
$category = get_the_category();
$the_category_id = $category[0]->cat_ID;
if(function_exists('rl_color'))
{
$rl_category_color = rl_color($the_category_id);
}
$sep = '';
foreach ((get_the_category()) as $cat) {
echo $sep . '<a href="' . get_category_link($cat->term_id) . '" class="' . $cat->slug . '" title="View all posts in '. esc_attr($cat->name) . '" style="background:' . $rl_category_color . '">' . $cat->cat_name . '</a>';
$sep = ', ';
}
?>
</code></pre>
| [
{
"answer_id": 237439,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Why you don't use \"Term meta\"?</p>\n\n<p><a href=\"https://www.smashingmagazine.com/2015/12/how-to-use-term-met... | 2016/08/29 | [
"https://wordpress.stackexchange.com/questions/237438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101827/"
] | I'm trying to give custom color to each **category item**, But it gives only one style to all items.
I use this plugin for the colors:
'[Category Color](https://wordpress.org/plugins/category-color/)'
My code as below,
```
<?php
$category = get_the_category();
$the_category_id = $category[0]->cat_ID;
if(function_exists('rl_color'))
{
$rl_category_color = rl_color($the_category_id);
}
$sep = '';
foreach ((get_the_category()) as $cat) {
echo $sep . '<a href="' . get_category_link($cat->term_id) . '" class="' . $cat->slug . '" title="View all posts in '. esc_attr($cat->name) . '" style="background:' . $rl_category_color . '">' . $cat->cat_name . '</a>';
$sep = ', ';
}
?>
``` | You are getting the color for one category (*term* is more appropriate though)
```
$the_category_id = $category[0]->cat_ID;
```
instead of checking the ID and Color for each term, that's why it's applying the same to all.
Try this (untested):
```
<?php
$categories = get_the_category();
$sep = '';
foreach ($categories as $cat) {
$the_category_id = $cat->term_id;
if(function_exists('rl_color')){
$rl_category_color = rl_color($the_category_id);
} else {
$rl_category_color = '#000'; // maybe a default color?
}
echo $sep . '<a href="' . get_category_link($cat->term_id) . '" class="' . $cat->slug . '" title="View all posts in '. esc_attr($cat->name) . '" style="background-color:' . $rl_category_color . '">' . $cat->cat_name . '</a>';
$sep = ', ';
}
?>
``` |
237,442 | <p>I need to get a post thumbnail to show up in an email, but this doesnt work with just <code>mailto</code>: as i've tried it.</p>
<pre><code><a href="mailto:?subject=Anbefalt innlegg - <?php the_title(); ?>&body=Hei, jeg fant et innlegg som jeg tror du vil like. <img src='<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>'>">
</code></pre>
<p>This only gives me the url, and the img tag doesnt work. Any ideas how to make this work? </p>
| [
{
"answer_id": 237445,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>The <code>mailto</code> protocol is fairly limited and does not support html in the body. Notably iOS supports so... | 2016/08/29 | [
"https://wordpress.stackexchange.com/questions/237442",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100922/"
] | I need to get a post thumbnail to show up in an email, but this doesnt work with just `mailto`: as i've tried it.
```
<a href="mailto:?subject=Anbefalt innlegg - <?php the_title(); ?>&body=Hei, jeg fant et innlegg som jeg tror du vil like. <img src='<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>'>">
```
This only gives me the url, and the img tag doesnt work. Any ideas how to make this work? | The `mailto` protocol is fairly limited and does not support html in the body. Notably iOS supports some tags, but you cannot rely on that. The point is that `mailto` parses information from the browser to the user's email program. The more tags are allowed, the higher the security risk becomes. So, if you insist on sending the mail using the remote mailing program, you're stuck.
The alternative is using [`wp_mail`](https://developer.wordpress.org/reference/functions/wp_mail/). Users could still click on a link, but in stead of to their mailing program, the will be brought to a (popup) page where can send their message. There are many plugins that do this. |
237,458 | <p>I have a custom post type <code>Portfolio</code> and each portfolio is a questionnaire. If I email the link of a portfolio to a client via email. </p>
<p>How can I expire link after 10 minutes, So if client has came after 10 minutes to visit the link Then there should be message that link has expired Please try again.</p>
<p>How can I do that?</p>
| [
{
"answer_id": 237472,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 0,
"selected": false,
"text": "<p>Here's one idea: Hook to the <code>template_redirect</code> action:</p>\n\n<p><a href=\"https://codex.wordpress.... | 2016/08/29 | [
"https://wordpress.stackexchange.com/questions/237458",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101087/"
] | I have a custom post type `Portfolio` and each portfolio is a questionnaire. If I email the link of a portfolio to a client via email.
How can I expire link after 10 minutes, So if client has came after 10 minutes to visit the link Then there should be message that link has expired Please try again.
How can I do that? | Ok I came up with this
```
add_action( 'wp_loaded', 'my_create_questionnaire_link');
function my_create_questionnaire_link(){
// this check is for demo, if you go to http://yoursite.demo/?create-my-link, you will get your unique url added to your content
if( isset( $_GET['create-my-link'] ) ){
// This filter is for demo purpose
// You might want to create a button or a special page to generate your
// unique URL
add_filter( 'the_content', function( $content ){
// This is the relevant part
// This code will create a unique link containing valid period and a nonce
$valid_period = 60 * 10; // 10 minutes
$expiry = current_time( 'timestamp', 1 ) + $valid_period; // current_time( 'timestamp' ) for your blog local timestamp
$url = site_url( '/path/to/your/portfolio/page' );
$url = add_query_arg( 'valid', $expiry, $url ); // Adding the timestamp to the url with the "valid" arg
$nonce_url = wp_nonce_url( $url, 'questionnaire_link_uid_' . $expiry, 'questionnaire' ); // Adding our nonce to the url with a unique id made from the expiry timestamp
// End of relevant part
// now here I return my nounce to the content of the post for demo purposed
// You would use this code when a button is pressed or when a special page is visited
$content .= $nonce_url;
return $content;
} );
}
}
```
This is where you would check for the validity of the unique URL
```
add_action( 'template_redirect', 'my_url_check' );
function my_url_check(){
if( isset( $_GET['questionnaire'] )){
// if the nonce fails, redirect to homepage
if( ! wp_verify_nonce( $_GET['questionnaire'], 'questionnaire_link_uid_' . $_GET['valid'] ) ){
wp_safe_redirect( site_url() );
exit;
}
// if timestamp is not valid, redirect to homepage
if( $_GET['valid'] < current_time( 'timestamp', 1) ){
wp_safe_redirect( site_url() );
exit;
}
// Show your content as normal if all verification passes.
}
}
``` |
237,461 | <p>Hello every one i am facing one issue in adding logo option in my theme panel of wordpress i am using this code</p>
<pre><code>function logo_display()
{
?>
<input type="file" name="logo" />
<?php echo get_option('logo'); ?>
<?php
}
function handle_logo_upload()
{
if(!empty($_FILES["demo-file"]["tmp_name"]))
{
$urls = wp_handle_upload($_FILES["logo"], array('test_form' => FALSE));
$temp = $urls["url"];
return $temp;
}
return $option;
}
function display_theme_panel_fields()
{
add_settings_section("section", "All Settings", null, "theme-options");
add_settings_field("logo", "Logo", "logo_display", "theme-options", "section");
register_setting("section", "logo", "handle_logo_upload");
}
add_action("admin_init", "display_theme_panel_fields");
</code></pre>
<p>The issue is its not saving logo and also not displaying it in admin as well. I have tried this 10 times with different ways but this code is not working. Please look in this code and help me in it please.</p>
| [
{
"answer_id": 237714,
"author": "shamim khan",
"author_id": 98304,
"author_profile": "https://wordpress.stackexchange.com/users/98304",
"pm_score": 2,
"selected": true,
"text": "<p>if you use wordpress customizer then try this code</p>\n\n<pre><code>public static function register ( $wp... | 2016/08/29 | [
"https://wordpress.stackexchange.com/questions/237461",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98358/"
] | Hello every one i am facing one issue in adding logo option in my theme panel of wordpress i am using this code
```
function logo_display()
{
?>
<input type="file" name="logo" />
<?php echo get_option('logo'); ?>
<?php
}
function handle_logo_upload()
{
if(!empty($_FILES["demo-file"]["tmp_name"]))
{
$urls = wp_handle_upload($_FILES["logo"], array('test_form' => FALSE));
$temp = $urls["url"];
return $temp;
}
return $option;
}
function display_theme_panel_fields()
{
add_settings_section("section", "All Settings", null, "theme-options");
add_settings_field("logo", "Logo", "logo_display", "theme-options", "section");
register_setting("section", "logo", "handle_logo_upload");
}
add_action("admin_init", "display_theme_panel_fields");
```
The issue is its not saving logo and also not displaying it in admin as well. I have tried this 10 times with different ways but this code is not working. Please look in this code and help me in it please. | if you use wordpress customizer then try this code
```
public static function register ( $wp_customize ) {
// Logo upload
$wp_customize->add_section( 'bia_logo_section' , array(
'title' => __( 'Site Logo', 'bia' ),
'priority' => 30,
'description' => 'Upload a logo to replace the default site name and description in the header',
) );
$wp_customize->add_setting( 'bia_logo', array(
'sanitize_callback' => 'esc_url_raw',
) );
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'bia_logo', array(
'label' => __( 'Site Logo', 'bia' ),
'section' => 'bia_logo_section',
'settings' => 'bia_logo',
) ) );
}
```
i think you can also try [redux framework](https://reduxframework.com/) for admin panel option |
237,488 | <p>I'm making my first wordpress site. When I publish a post I see it in my home page but despite I add an image I can't see it above the post title in my home page. <a href="https://i.stack.imgur.com/EnztZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EnztZ.jpg" alt="enter image description here"></a></p>
<p>Thank you in advice.</p>
| [
{
"answer_id": 237714,
"author": "shamim khan",
"author_id": 98304,
"author_profile": "https://wordpress.stackexchange.com/users/98304",
"pm_score": 2,
"selected": true,
"text": "<p>if you use wordpress customizer then try this code</p>\n\n<pre><code>public static function register ( $wp... | 2016/08/29 | [
"https://wordpress.stackexchange.com/questions/237488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101850/"
] | I'm making my first wordpress site. When I publish a post I see it in my home page but despite I add an image I can't see it above the post title in my home page. [](https://i.stack.imgur.com/EnztZ.jpg)
Thank you in advice. | if you use wordpress customizer then try this code
```
public static function register ( $wp_customize ) {
// Logo upload
$wp_customize->add_section( 'bia_logo_section' , array(
'title' => __( 'Site Logo', 'bia' ),
'priority' => 30,
'description' => 'Upload a logo to replace the default site name and description in the header',
) );
$wp_customize->add_setting( 'bia_logo', array(
'sanitize_callback' => 'esc_url_raw',
) );
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'bia_logo', array(
'label' => __( 'Site Logo', 'bia' ),
'section' => 'bia_logo_section',
'settings' => 'bia_logo',
) ) );
}
```
i think you can also try [redux framework](https://reduxframework.com/) for admin panel option |
237,558 | <h2>Introduction</h2>
<p>When uploading a file (<code>stackexchange.jpg</code>) to the media library in a WordPress site, there are two relevant links.</p>
<ol>
<li><p><strong>Direct link to file</strong><br><code>http://example.com/wp-content/uploads/stackexchange.jpg</code></p></li>
<li><p><strong>Attachment page</strong><br><code>http://example.com/stackexchange/</code></p></li>
</ol>
<p>My question deals with the second one: <em>attachment page</em>.</p>
<h2>What I Want to Do</h2>
<p>I would like to add the file extension in the attachment page permalink. For example, instead of</p>
<p><code>http://example.com/stackexchange/</code></p>
<p>I would like</p>
<p><code>http://example.com/stackexchange-jpg/</code></p>
<h3>Why This Would be Useful</h3>
<p>This would be very useful for a couple of reasons. For one, it won't be <a href="https://wordpress.stackexchange.com/questions/217848/media-items-hogging-pretty-permalinks">hogging permalinks</a> in case I want to use it for a post or a page, etc. For another, I can then upload another file called <code>stackexchange.png</code>. Then, I would have:<br>
<code>http://example.com/stackexchange-jpg/</code><br>
and<br>
<code>http://example.com/stackexchange-png/</code></p>
<p>And again, I can still use <code>http://example.com/stackexchange/</code> for an actual page.</p>
<p>I do realize that I <em>can</em> go through and edit every single file's slug manually, which in turn would indeed change the attachment page permalink, but I think it almost goes without saying that I wouldn't need to actually make a thread if I was looking to do that.</p>
<h2>Question</h2>
<p>Is there a function I can write to make it so that whenever a file is uploaded, it reflects the changes I'm looking for? Is this even possible? If so, how do I do it? If you know how to edit the default permalink, but you don't know how to add the file extension part, I can most likely still work with that information.</p>
<p>I'm thinking this is probably not possible without tampering with core files (which would be a deal breaker), but hopefully it is.</p>
<p>Thanks for reading and for any help.</p>
| [
{
"answer_id": 238205,
"author": "KenB",
"author_id": 27576,
"author_profile": "https://wordpress.stackexchange.com/users/27576",
"pm_score": 2,
"selected": true,
"text": "<p>Great question! I've been thinking about this myself and your question prompted me to dig into it.</p>\n\n<p>Ther... | 2016/08/30 | [
"https://wordpress.stackexchange.com/questions/237558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88601/"
] | Introduction
------------
When uploading a file (`stackexchange.jpg`) to the media library in a WordPress site, there are two relevant links.
1. **Direct link to file**
`http://example.com/wp-content/uploads/stackexchange.jpg`
2. **Attachment page**
`http://example.com/stackexchange/`
My question deals with the second one: *attachment page*.
What I Want to Do
-----------------
I would like to add the file extension in the attachment page permalink. For example, instead of
`http://example.com/stackexchange/`
I would like
`http://example.com/stackexchange-jpg/`
### Why This Would be Useful
This would be very useful for a couple of reasons. For one, it won't be [hogging permalinks](https://wordpress.stackexchange.com/questions/217848/media-items-hogging-pretty-permalinks) in case I want to use it for a post or a page, etc. For another, I can then upload another file called `stackexchange.png`. Then, I would have:
`http://example.com/stackexchange-jpg/`
and
`http://example.com/stackexchange-png/`
And again, I can still use `http://example.com/stackexchange/` for an actual page.
I do realize that I *can* go through and edit every single file's slug manually, which in turn would indeed change the attachment page permalink, but I think it almost goes without saying that I wouldn't need to actually make a thread if I was looking to do that.
Question
--------
Is there a function I can write to make it so that whenever a file is uploaded, it reflects the changes I'm looking for? Is this even possible? If so, how do I do it? If you know how to edit the default permalink, but you don't know how to add the file extension part, I can most likely still work with that information.
I'm thinking this is probably not possible without tampering with core files (which would be a deal breaker), but hopefully it is.
Thanks for reading and for any help. | Great question! I've been thinking about this myself and your question prompted me to dig into it.
There is a filter `wp_insert_attachment_data` than can be used to fix the slug name for uploaded files. It is called for attachments shortly before the attachment is inserted into the database in `post.php`.
The following sample will append the mime type to the slug name, for example `image-jpg` will be added to a jpeg image title.
```
/**
* Filter attachment post data before it is added to the database
* - Add mime type to post_name to reduce slug collisions
*
* @param array $data Array of santized attachment post data
* @param array $postarr Array of unsanitized attachment post data
* @return $data, array of post data
*/
function filter_attachment_slug($data, $postarr)
{
/**
* Only work on attachment types
*/
if ( ! array_key_exists( 'post_type', $data ) || 'attachment' != $data['post_type'] )
return $data;
/**
* Add mime type to the post title to build post-name
*/
$post_title = array_key_exists( 'post_title', $data ) ? $data['post_title'] : $postarr['post_title'];
$post_mime_type = array_key_exists( 'post_mime_type', $data ) ? $data['post_mime_type'] : $postarr['post_mime_type'];
$post_mime_type = str_replace( '/', '-', $post_mime_type );
$post_name = sanitize_title( $post_title . '-' . $post_mime_type );
/**
* Generate unique slug for post name
*/
$post_ID = array_key_exists( 'ID', $data ) ? $data['ID'] : $postarr['ID'];
$post_status = array_key_exists( 'post_status', $data ) ? $data['post_status'] : $postarr['post_status'];
$post_type = array_key_exists( 'post_type', $data ) ? $data['post_type'] : $postarr['post_type'];
$post_parent = array_key_exists( 'post_parent', $data ) ? $data['post_parent'] : $postarr['post_parent'];
$post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
$data['post_name'] = $post_name;
return $data;
}
/**
* Adjust slug for uploaded files to include mime type
*/
add_filter( 'wp_insert_attachment_data', 'filter_attachment_slug', 10, 2 );
``` |
237,573 | <p>I'm trying to add a CSS class to every image in a custom post type. </p>
<p>I've found <a href="https://wordpress.stackexchange.com/questions/108831/add-css-class-to-every-image">this answer</a>, to add a class to every image in general: </p>
<pre><code>function add_image_class($class){
$class .= ' additional-class';
return $class;
}
add_filter('get_image_tag_class','add_image_class');
</code></pre>
<p>How would I build on this, so that it only applies to a custom post type? </p>
| [
{
"answer_id": 237575,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>The function <a href=\"https://developer.wordpress.org/reference/functions/get_post_type/\" rel=\"nofollow\"><co... | 2016/08/30 | [
"https://wordpress.stackexchange.com/questions/237573",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92868/"
] | I'm trying to add a CSS class to every image in a custom post type.
I've found [this answer](https://wordpress.stackexchange.com/questions/108831/add-css-class-to-every-image), to add a class to every image in general:
```
function add_image_class($class){
$class .= ' additional-class';
return $class;
}
add_filter('get_image_tag_class','add_image_class');
```
How would I build on this, so that it only applies to a custom post type? | Combining the answer here by @cjcj with the code in [this answer](https://wordpress.stackexchange.com/a/22166/92868), the code that works for me outside the loop, in functions.php is:
```
// Add ability to check for custom post type outside the loop.
function is_post_type($type){
global $wp_query;
if($type == get_post_type($wp_query->post->ID)) return true;
return false;
}
// Add class to every image in 'wpse' custom post type.
function add_image_class($class){
if ('wpse' == is_post_type()){
$class .= ' additional-class';
}
return $class;
}
add_filter('get_image_tag_class','add_image_class');
``` |
237,599 | <p>Depending on the product category, I have different data to display on category page. I'm getting my category <code>ID</code> this way:</p>
<pre><code><?php global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
if ($product_cat_id == "6") {
echo "aaa";
}
elseif ($product_cat_id == "7") {
echo "bbb";
}
?>
</code></pre>
<p>But I need to display different data when product is in two categories and it does not work.</p>
<pre><code>echo $product_cat_id;
</code></pre>
<p>It recognizes only one category. How do I make it recognize two and make <code>IF</code> statement for product which is in category 6 <code>AND</code> 7?</p>
| [
{
"answer_id": 237603,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 0,
"selected": false,
"text": "<p>Your <code>$product_cat_id</code> is an <code>array()</code> of all of your categories and it looks ... | 2016/08/30 | [
"https://wordpress.stackexchange.com/questions/237599",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101907/"
] | Depending on the product category, I have different data to display on category page. I'm getting my category `ID` this way:
```
<?php global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
if ($product_cat_id == "6") {
echo "aaa";
}
elseif ($product_cat_id == "7") {
echo "bbb";
}
?>
```
But I need to display different data when product is in two categories and it does not work.
```
echo $product_cat_id;
```
It recognizes only one category. How do I make it recognize two and make `IF` statement for product which is in category 6 `AND` 7? | >
> Try This Code
>
>
>
```
<?php global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
if ($product_cat_id == "6" && $product_cat_id == "7" ) {
echo "aaabbb";
}
else if ($product_cat_id == "6" ) {
echo "aaa";
}
else if ($product_cat_id == "7") {
echo "bbb";
}
?>
``` |
237,601 | <p>I am currently making an e-shop on woocommerce. On my homepage there is products slider with the add-to-cart button under each product. If I click on the button, product is added to cart successfully, but without any message.</p>
<p>While surfing the Internet, I've found out, that messages can be added on shop page, product category page and product tag page (<a href="https://www.skyverge.com/blog/display-woocommerce-cart-notices/" rel="nofollow">in this article</a>). According to that article, I should use filter/hook to catch the add-to-cart event and display message on main page.</p>
<p>I have tried this:</p>
<pre><code> add_filter( 'woocommerce_add_to_cart_message', 'custom_add_to_cart_message' );
function custom_add_to_cart_message() {
global $woocommerce;
// Output success messages
if (get_option('woocommerce_cart_redirect_after_add')=='yes') :
$return_to = get_permalink(woocommerce_get_page_id('shop'));
$message = sprintf('<a href="%s" class="button">%s</a> %s', $return_to, __('Continue Shopping &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
else :
$message = sprintf('<a href="%s" class="button">%s</a> %s', get_permalink(woocommerce_get_page_id('cart')), __('View Cart &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
endif;
return $message;
}
</code></pre>
<p>but nothing happens. Can anyone help me? </p>
| [
{
"answer_id": 237602,
"author": "Faisal Ramzan",
"author_id": 85487,
"author_profile": "https://wordpress.stackexchange.com/users/85487",
"pm_score": 2,
"selected": false,
"text": "<p>This article will help you in this issue\n<a href=\"https://docs.woocommerce.com/document/woocommerce-c... | 2016/08/30 | [
"https://wordpress.stackexchange.com/questions/237601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80324/"
] | I am currently making an e-shop on woocommerce. On my homepage there is products slider with the add-to-cart button under each product. If I click on the button, product is added to cart successfully, but without any message.
While surfing the Internet, I've found out, that messages can be added on shop page, product category page and product tag page ([in this article](https://www.skyverge.com/blog/display-woocommerce-cart-notices/)). According to that article, I should use filter/hook to catch the add-to-cart event and display message on main page.
I have tried this:
```
add_filter( 'woocommerce_add_to_cart_message', 'custom_add_to_cart_message' );
function custom_add_to_cart_message() {
global $woocommerce;
// Output success messages
if (get_option('woocommerce_cart_redirect_after_add')=='yes') :
$return_to = get_permalink(woocommerce_get_page_id('shop'));
$message = sprintf('<a href="%s" class="button">%s</a> %s', $return_to, __('Continue Shopping →', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
else :
$message = sprintf('<a href="%s" class="button">%s</a> %s', get_permalink(woocommerce_get_page_id('cart')), __('View Cart →', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
endif;
return $message;
}
```
but nothing happens. Can anyone help me? | Solution was as simple as it should be: I've just added this piece of code into my main page .php file:
```
do_action( 'woocommerce_before_single_product' );
``` |
237,610 | <p>Here is my query args :</p>
<pre><code> $query_args = array(
'post_type' => 'rented_properties',
'post_status' => 'publish',
'order' => 'DESC',
// 'fields' => 'SUM(amount_to_paid)',
);
$my_querys = null;
$my_querys = new WP_Query($query_args);
</code></pre>
<p>My meta key is <code>amount_to_paid</code>, and I want to get the sum all the meta_values of this query condition. Please suggest your answer with <code>query_args</code>.</p>
<p>My Scenario : I have 1000 posts and each with meta_key amount_to_paid and it has some value. Now I filter 20 posts and want to get sum of meta_value of amount_to_paid . Did you got me now?</p>
| [
{
"answer_id": 237711,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p><code>WP_Query</code> gets posts from the database, but it's not a generic SQL query class, it should really ... | 2016/08/30 | [
"https://wordpress.stackexchange.com/questions/237610",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99113/"
] | Here is my query args :
```
$query_args = array(
'post_type' => 'rented_properties',
'post_status' => 'publish',
'order' => 'DESC',
// 'fields' => 'SUM(amount_to_paid)',
);
$my_querys = null;
$my_querys = new WP_Query($query_args);
```
My meta key is `amount_to_paid`, and I want to get the sum all the meta\_values of this query condition. Please suggest your answer with `query_args`.
My Scenario : I have 1000 posts and each with meta\_key amount\_to\_paid and it has some value. Now I filter 20 posts and want to get sum of meta\_value of amount\_to\_paid . Did you got me now? | `WP_Query` gets posts from the database, but it's not a generic SQL query class, it should really be called `WP_Post_Query`, as `WP_Query` implies it can do any SQL.
As a result, you need to do several things:
1. Grab the posts you need
2. Get their meta values for `amount_to_paid` using `get_post_meta`
3. Add those values up using the basic PHP maths `+ - / * = += -=`
So:
```
$sum = 0;
$query = new WP_Query($query_args);
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// do the processing for each post
$sum = $sum + get_post_meta( ... );
}
}
echo esc_html( $sum );
``` |
237,613 | <p>I'm using WP version 4.4.4. I have some posts where it has a continue reading button and link to the actual excerpt. My problem is the excerpt also has a continue reading button. Here is my code at the end of <code>functions.php</code>.</p>
<pre><code>function new_excerpt_more($more) {
global $post;
return '... <a class="moretag" href="'. get_permalink($post->ID). '"> continue reading &raquo;</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
</code></pre>
<p>Fairly new to WordPress. I searched this site but nothing worked for me. Thanks.</p>
| [
{
"answer_id": 237711,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p><code>WP_Query</code> gets posts from the database, but it's not a generic SQL query class, it should really ... | 2016/08/30 | [
"https://wordpress.stackexchange.com/questions/237613",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91536/"
] | I'm using WP version 4.4.4. I have some posts where it has a continue reading button and link to the actual excerpt. My problem is the excerpt also has a continue reading button. Here is my code at the end of `functions.php`.
```
function new_excerpt_more($more) {
global $post;
return '... <a class="moretag" href="'. get_permalink($post->ID). '"> continue reading »</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
```
Fairly new to WordPress. I searched this site but nothing worked for me. Thanks. | `WP_Query` gets posts from the database, but it's not a generic SQL query class, it should really be called `WP_Post_Query`, as `WP_Query` implies it can do any SQL.
As a result, you need to do several things:
1. Grab the posts you need
2. Get their meta values for `amount_to_paid` using `get_post_meta`
3. Add those values up using the basic PHP maths `+ - / * = += -=`
So:
```
$sum = 0;
$query = new WP_Query($query_args);
if ( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
// do the processing for each post
$sum = $sum + get_post_meta( ... );
}
}
echo esc_html( $sum );
``` |
237,620 | <p>I am developing a wordpress theme. In <code>single.php</code> page I want to loop similar to this,</p>
<pre><code><?php while ( have_posts() ) : the_post(); ?>
<?php if ( is_single() ) : ?>
<div class="post-heading-info">
<!--Post heading info like title, category goes here -->
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php //sidebar widget goes here ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php if ( is_single() ) : ?>
<div class="post-content">
<!--Post content and footer goes here-->
</div>
<?php endif; ?>
<?php endwhile; ?>
</code></pre>
<p>So, in the code above I am trying to loop all the basic information like title, category and time. The In the middle I want to put the sidebar and then in the second loop the content and the post's footer information. </p>
<p>I need this because of various options in single.php page layout. Basically I want keep all header info on top above all the widgets and post contents. </p>
<p>My question is, <strong>Is this the code above acceptable as a good practice?</strong></p>
<p>Please help me in this and your few minutes from your life for my question would be really appreciated and helpful. </p>
| [
{
"answer_id": 237621,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": false,
"text": "<p>As many people would agree, editing WordPress' core is not recommended because any updates that are ... | 2016/08/30 | [
"https://wordpress.stackexchange.com/questions/237620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89234/"
] | I am developing a wordpress theme. In `single.php` page I want to loop similar to this,
```
<?php while ( have_posts() ) : the_post(); ?>
<?php if ( is_single() ) : ?>
<div class="post-heading-info">
<!--Post heading info like title, category goes here -->
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php //sidebar widget goes here ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php if ( is_single() ) : ?>
<div class="post-content">
<!--Post content and footer goes here-->
</div>
<?php endif; ?>
<?php endwhile; ?>
```
So, in the code above I am trying to loop all the basic information like title, category and time. The In the middle I want to put the sidebar and then in the second loop the content and the post's footer information.
I need this because of various options in single.php page layout. Basically I want keep all header info on top above all the widgets and post contents.
My question is, **Is this the code above acceptable as a good practice?**
Please help me in this and your few minutes from your life for my question would be really appreciated and helpful. | As many people would agree, editing WordPress' core is not recommended because any updates that are made from the official developer (ex: 4.6 to 4.6.1) will override your changes. Plus, editing the core could potentially break your website or any other theme/plugin if it's not properly edited.
This is where plugins come in, they are packed functions that acts as an add on to enhance your WordPress site.
However, if you do not want to use a plugin to achieve this functionality. Your best solution is to add your custom code in your child theme's `functions.php` file which runs your custom codes on top of WordPress.
### Update: per [Youssef's comment below](https://wordpress.stackexchange.com/questions/237619#comment354057_237621)
>
> ...what code should I add to `functions.php` to get users to verify their email?
>
>
>
It wouldn't be a few lines of code to add to your `functions.php`, I can tell you that much.
This will require some work and research on your end since I can't write up something like this. The right approach is to try and solve this question yourself with your own function. Then, when you run into an issue you can't solve, that's where the [WPSE](http://s.tk/wp) community is here for.
>
> *We don't want our members to ask people to create a solution without attempting it themselves.*
>
>
>
To start, I'd look into other [plugins](https://wordpress.org/plugins/) or [functions](https://wordpress.stackexchange.com/questions/tagged/functions) that are available tailor the codes for yourself. For example, this plugin: [User Activation Email](https://wordpress.org/plugins/user-activation-email/) is worth looking into. Just download the `.zip` file and play around with the source codes.
Otherwise, if you are not comfortable with any of this, your best bet is to utilize a plugin that already exists. As I mentioned in my original answer, *editing WordPress' core is not recommended*. |
237,629 | <p>I can think of a number of ways to go about doing this. I'm looking for the most efficient way. Menu looks like this:</p>
<p>catArchive1 [num_new_posts] catArchive2 [num_new_posts] catArchive3 [num_new_posts]</p>
<p>^^[num_new_posts] being the number of new posts</p>
<p>Assuming we have a cookie value set for the users last visit <code>$_COOKIE['lastvisit']</code>.</p>
<p>I could do something like the follow for EACH menu/category</p>
<pre><code>$args = array(
'category' => $cat_id,
'posts_per_page' => -1,
'date_query' => array( 'after' => $_COOKIE['lastvisit'] ),
);
$new_posts = get_posts($args);
$num_posts = count($num_posts); // Number of new posts
</code></pre>
<p>Of course, this is another query for each menu item. Any ideas how to combine this into one and still know how many new posts in each category? </p>
| [
{
"answer_id": 237621,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": false,
"text": "<p>As many people would agree, editing WordPress' core is not recommended because any updates that are ... | 2016/08/30 | [
"https://wordpress.stackexchange.com/questions/237629",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11857/"
] | I can think of a number of ways to go about doing this. I'm looking for the most efficient way. Menu looks like this:
catArchive1 [num\_new\_posts] catArchive2 [num\_new\_posts] catArchive3 [num\_new\_posts]
^^[num\_new\_posts] being the number of new posts
Assuming we have a cookie value set for the users last visit `$_COOKIE['lastvisit']`.
I could do something like the follow for EACH menu/category
```
$args = array(
'category' => $cat_id,
'posts_per_page' => -1,
'date_query' => array( 'after' => $_COOKIE['lastvisit'] ),
);
$new_posts = get_posts($args);
$num_posts = count($num_posts); // Number of new posts
```
Of course, this is another query for each menu item. Any ideas how to combine this into one and still know how many new posts in each category? | As many people would agree, editing WordPress' core is not recommended because any updates that are made from the official developer (ex: 4.6 to 4.6.1) will override your changes. Plus, editing the core could potentially break your website or any other theme/plugin if it's not properly edited.
This is where plugins come in, they are packed functions that acts as an add on to enhance your WordPress site.
However, if you do not want to use a plugin to achieve this functionality. Your best solution is to add your custom code in your child theme's `functions.php` file which runs your custom codes on top of WordPress.
### Update: per [Youssef's comment below](https://wordpress.stackexchange.com/questions/237619#comment354057_237621)
>
> ...what code should I add to `functions.php` to get users to verify their email?
>
>
>
It wouldn't be a few lines of code to add to your `functions.php`, I can tell you that much.
This will require some work and research on your end since I can't write up something like this. The right approach is to try and solve this question yourself with your own function. Then, when you run into an issue you can't solve, that's where the [WPSE](http://s.tk/wp) community is here for.
>
> *We don't want our members to ask people to create a solution without attempting it themselves.*
>
>
>
To start, I'd look into other [plugins](https://wordpress.org/plugins/) or [functions](https://wordpress.stackexchange.com/questions/tagged/functions) that are available tailor the codes for yourself. For example, this plugin: [User Activation Email](https://wordpress.org/plugins/user-activation-email/) is worth looking into. Just download the `.zip` file and play around with the source codes.
Otherwise, if you are not comfortable with any of this, your best bet is to utilize a plugin that already exists. As I mentioned in my original answer, *editing WordPress' core is not recommended*. |
237,671 | <p>I have website in WordPress and I updated my <code>.htaccess</code> file with following rule. </p>
<pre><code><IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
</IfModule>
</code></pre>
<p>Now, when I checked my website performance with <a href="https://developers.google.com/speed/pagespeed/insights/" rel="nofollow">Google insight</a>. it still giving me error for <strong>leverage browser caching</strong></p>
<p>I have used this code </p>
<pre><code> add_filter( 'script_loader_src', 'elated_child__remove_ver' );
add_filter( 'style_loader_src', 'elated_child__remove_ver' );
function elated_child__remove_ver( $src ) { // Remove query strings from static resources
if ( strpos( $src, '?f=' ) || strpos( $src, '&f=' ) ) {
$src = remove_query_arg( 'f', $src );
}
return $src;
}
</code></pre>
<p>Any idea?</p>
| [
{
"answer_id": 237621,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 1,
"selected": false,
"text": "<p>As many people would agree, editing WordPress' core is not recommended because any updates that are ... | 2016/08/31 | [
"https://wordpress.stackexchange.com/questions/237671",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101535/"
] | I have website in WordPress and I updated my `.htaccess` file with following rule.
```
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
</IfModule>
```
Now, when I checked my website performance with [Google insight](https://developers.google.com/speed/pagespeed/insights/). it still giving me error for **leverage browser caching**
I have used this code
```
add_filter( 'script_loader_src', 'elated_child__remove_ver' );
add_filter( 'style_loader_src', 'elated_child__remove_ver' );
function elated_child__remove_ver( $src ) { // Remove query strings from static resources
if ( strpos( $src, '?f=' ) || strpos( $src, '&f=' ) ) {
$src = remove_query_arg( 'f', $src );
}
return $src;
}
```
Any idea? | As many people would agree, editing WordPress' core is not recommended because any updates that are made from the official developer (ex: 4.6 to 4.6.1) will override your changes. Plus, editing the core could potentially break your website or any other theme/plugin if it's not properly edited.
This is where plugins come in, they are packed functions that acts as an add on to enhance your WordPress site.
However, if you do not want to use a plugin to achieve this functionality. Your best solution is to add your custom code in your child theme's `functions.php` file which runs your custom codes on top of WordPress.
### Update: per [Youssef's comment below](https://wordpress.stackexchange.com/questions/237619#comment354057_237621)
>
> ...what code should I add to `functions.php` to get users to verify their email?
>
>
>
It wouldn't be a few lines of code to add to your `functions.php`, I can tell you that much.
This will require some work and research on your end since I can't write up something like this. The right approach is to try and solve this question yourself with your own function. Then, when you run into an issue you can't solve, that's where the [WPSE](http://s.tk/wp) community is here for.
>
> *We don't want our members to ask people to create a solution without attempting it themselves.*
>
>
>
To start, I'd look into other [plugins](https://wordpress.org/plugins/) or [functions](https://wordpress.stackexchange.com/questions/tagged/functions) that are available tailor the codes for yourself. For example, this plugin: [User Activation Email](https://wordpress.org/plugins/user-activation-email/) is worth looking into. Just download the `.zip` file and play around with the source codes.
Otherwise, if you are not comfortable with any of this, your best bet is to utilize a plugin that already exists. As I mentioned in my original answer, *editing WordPress' core is not recommended*. |
237,741 | <p>I need to protect some hooks which only can be hooked by functions/callbacks within my theme/plugin.</p>
<p>For example:</p>
<pre><code>if ( is_protected_hook('hook_name') ) {
throw new \Exception('You cannot hook to a protected hook.');
} else {
do_action('hook_name');
}
</code></pre>
<p>Is there a way to define the <code>is_protected_hook()</code> function?</p>
<p>Any suggestions will be greatly appreciated! </p>
| [
{
"answer_id": 237748,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>As noted in my answer to <a href=\"https://wordpress.stackexchange.com/questions/237717/how-to-check-if-a-hook-is... | 2016/08/31 | [
"https://wordpress.stackexchange.com/questions/237741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92212/"
] | I need to protect some hooks which only can be hooked by functions/callbacks within my theme/plugin.
For example:
```
if ( is_protected_hook('hook_name') ) {
throw new \Exception('You cannot hook to a protected hook.');
} else {
do_action('hook_name');
}
```
Is there a way to define the `is_protected_hook()` function?
Any suggestions will be greatly appreciated! | As noted in my answer to [your related question](https://wordpress.stackexchange.com/questions/237717/how-to-check-if-a-hook-is-hooked-or-not) there is a datastructre `$wp_filter` that stores all information on hooks and filters. You may want to try a `var_dump` on it just to see what it looks like. There is no built in variable 'protected'.
This leaves you with two options to keep the administration of the hooks you want to protect: build it into `$wp_filter` yourself or keep it separate. I recommend the latter.
Maintain an array `$protected_hooks`. I don't know the conditions under which you want hooks to be protected, but you will have to set this array the moment you add an action to a specific hook.
Now, in your tempate file you will need a double condition: is a hook active and is it protected. That would go like this:
```
if ((has_filter('hook_name') && in_array('hook_name',$protected_hooks)) ...
``` |
237,757 | <p>I have the following code (below) in my theme. I am using redux framework for my theme options. My codes in a part looking like this. And I am really not sure about the security issue of this chunk of codes. Please any expert help me indicating any security problem in here. Your few minutes from your life would be really appreciated and helpful. </p>
<pre><code><?php if (isset($cosomic_options['blog_tag']) && $cosomic_options['blog_tag'] ) { ?>
<div class="entry-meta-tag">
<?php the_tags('', ' ', '<br />'); ?>
</div>
<?php } ?>
<div class="entry-content">
<p>
<?php $content = get_the_content();
echo wp_trim_words( $content , '35' );
?>
</p>
</div>
<?php $continue_reading = ''; ?>
<?php if (isset($cosomic_options['blog_continue_en']) && $cosomic_options['blog_continue_en'] ) { ?>
<?php if (isset($cosomic_options['blog_continue_en']) && $cosomic_options['blog_continue_en'] ) {
if ( isset($cosomic_options['blog_continue']) && $cosomic_options['blog_continue'] ) {
$continue_reading = $cosomic_options['blog_continue'];
}else {
$continue_reading = 'Continue Reading';
} ?>
<div class="a-btn">
<a href="<?php the_permalink(); ?>"><?php echo $continue_reading; ?> <i class="fa fa-hand-o-right"></i></a>
</div>
<?php } ?>
<?php } ?>
</code></pre>
| [
{
"answer_id": 237759,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 3,
"selected": true,
"text": "<p>Security issues arise when you write code that open up possibilities for outsiders to access your database or oth... | 2016/08/31 | [
"https://wordpress.stackexchange.com/questions/237757",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89234/"
] | I have the following code (below) in my theme. I am using redux framework for my theme options. My codes in a part looking like this. And I am really not sure about the security issue of this chunk of codes. Please any expert help me indicating any security problem in here. Your few minutes from your life would be really appreciated and helpful.
```
<?php if (isset($cosomic_options['blog_tag']) && $cosomic_options['blog_tag'] ) { ?>
<div class="entry-meta-tag">
<?php the_tags('', ' ', '<br />'); ?>
</div>
<?php } ?>
<div class="entry-content">
<p>
<?php $content = get_the_content();
echo wp_trim_words( $content , '35' );
?>
</p>
</div>
<?php $continue_reading = ''; ?>
<?php if (isset($cosomic_options['blog_continue_en']) && $cosomic_options['blog_continue_en'] ) { ?>
<?php if (isset($cosomic_options['blog_continue_en']) && $cosomic_options['blog_continue_en'] ) {
if ( isset($cosomic_options['blog_continue']) && $cosomic_options['blog_continue'] ) {
$continue_reading = $cosomic_options['blog_continue'];
}else {
$continue_reading = 'Continue Reading';
} ?>
<div class="a-btn">
<a href="<?php the_permalink(); ?>"><?php echo $continue_reading; ?> <i class="fa fa-hand-o-right"></i></a>
</div>
<?php } ?>
<?php } ?>
``` | Security issues arise when you write code that open up possibilities for outsiders to access your database or otherwise compromise your installation.
The above code just reads options and content from the database and translates this into static html that will be send to the browser of the page's visitor. There's no code (like a `form`) that will allow the visitor to send information back to your server. So there are no security concerns.
(Of course there still could be vulnerabilities in other parts of your code.) |
237,762 | <p>I would like to disable all attachment pages completely. I Googled it, but there's just information on <a href="https://stackoverflow.com/questions/28885293/how-disable-image-attachment-pages-in-wordpress">how to redirect to parent post or homepage</a>. That's not what I would call an elegant solution. Why introduce unnecessary permalinks that redirect to the homepage? Couldn't it be disabled completely? </p>
| [
{
"answer_id": 271089,
"author": "Ihor Vorotnov",
"author_id": 47359,
"author_profile": "https://wordpress.stackexchange.com/users/47359",
"pm_score": 4,
"selected": false,
"text": "<p>You can filter default rewrite rules and remove those for attachments:</p>\n\n<pre><code>function clean... | 2016/08/31 | [
"https://wordpress.stackexchange.com/questions/237762",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88787/"
] | I would like to disable all attachment pages completely. I Googled it, but there's just information on [how to redirect to parent post or homepage](https://stackoverflow.com/questions/28885293/how-disable-image-attachment-pages-in-wordpress). That's not what I would call an elegant solution. Why introduce unnecessary permalinks that redirect to the homepage? Couldn't it be disabled completely? | You can filter default rewrite rules and remove those for attachments:
```
function cleanup_default_rewrite_rules( $rules ) {
foreach ( $rules as $regex => $query ) {
if ( strpos( $regex, 'attachment' ) || strpos( $query, 'attachment' ) ) {
unset( $rules[ $regex ] );
}
}
return $rules;
}
add_filter( 'rewrite_rules_array', 'cleanup_default_rewrite_rules' );
```
Don't forget to re-save your permalinks once. WordPress will generate new rules without anything related to attachments.
Now, the attachment page URL gives 404. You can also add that redirect to prevent the 404 page, it's useless in this case. But I'm not sure how to catch the redirect - is\_attachment() will not work if the rewrite rules are removed.
**Update:**
WordPress will still offer the attachment page pretty URLs in media library and media insertion dialog. You can filter this as well:
```
function cleanup_attachment_link( $link ) {
return;
}
add_filter( 'attachment_link', 'cleanup_attachment_link' );
```
In this case, even when you insert your attachment into post ans select "Link to attachment page", the image will be inserted **without the link**. |
237,816 | <p>I have build a custom post_type with "Resellers" in order to enter my personal reseller items. The "Resellers" post have taxonomies like "Countries" and "Departmens".</p>
<p>I am running into a problem:</p>
<p>The first time that the page is displayed, nothing gets fetched from my custom post type taxonomies. If I click on one of my links, then the data get successfully updated. The issue is Country without "Département" assigned category (Allemagne for example) = The results are displayed but the "Département" drop-list should be hidden.</p>
<p>Can anyone tell me where have I done a mistake ?</p>
<p><strong>function.php</strong></p>
<pre><code>if( !function_exists( 'reseller_department' ) ){
function reseller_department(){
$location = get_terms( 'reseller-department', array( 'parent' => 0 ) );
if( !empty($location) ){
foreach( $location as $term ){
if(isset($_GET['reseller_department']) ){
if($_GET['reseller_department'] == $term->slug ){
$selected = 'selected';
}else{
$selected = '';
}
}else{
$selected = '';
}
echo '<option value="'.$term->slug.'" '.$selected.'>'.$term->name.'</option>';
}
if(!isset($_GET['reseller_department']) || $_GET['reseller_department'] == '-1'){
echo '<option value="-1" selected>'.__( 'all departments', 'nalys-plugin' ).'</option>';
}else{
echo '<option value="-1">'.__( '…', 'nalys-plugin' ).'</option>';
}
}
}
}
if( !function_exists( 'reseller_country' ) ){
function reseller_country(){
$location = get_terms( 'reseller-country', array( 'parent' => 0 ) );
if( !empty($location) ){
foreach( $location as $term ){
if(isset($_GET['reseller_country']) ){
if($_GET['reseller_country'] == $term->slug ){
$selected = 'selected';
}else{
$selected = '';
}
}else{
$selected = '';
}
echo '<option value="'.$term->slug.'" '.$selected.'>'.$term->name.'</option>';
}
if(!isset($_GET['reseller_country']) || $_GET['reseller_country'] == '-1'){
echo '<option value="-1" selected>'.__( '...', 'nalys-plugin' ).'</option>';
}else{
echo '<option value="-1">'.__( '…', 'nalys-plugin' ).'</option>';
}
}
}
}
</code></pre>
<p><strong>archieve.js</strong></p>
<pre><code>jQuery(document).ready(function($) {
$("#archive-wrapper").height($("#archive-pot").height());
$("#archive-browser select").change(function() {
$("#archive-pot")
.empty()
.html("<div style='text-align: center; padding: 30px;'>Loading...</div>");
var d = $("#reseller_department").val();
var e = $("#reseller_country").val();
$.ajax({
url: "/work/",
dataType: "html",
type: "POST",
data: {
"digwp_d" : d,
"digwp_e" : e
},
success: function(data) {
$("#archive-pot").html(data);
$("#archive-wrapper").animate({
height: $("#archives-table tr").length * 50
});
}
});
});
// get all data option value reseller country
var values = [];
var sel = document.getElementById('reseller_country');
for (var i=0, n=sel.options.length;i<n;i++) {
if (sel.options[i].value)
values.push(sel.options[i].value);
}
var jupe = '"' + values.join('","') + '"';
var dataOptionCountry = values;
dataOptionCountry.pop();
// console.log(dataOptionCountry);
$("#reseller_country").change(function () {
$("#reseller_department").prop("disabled", !(dataOptionCountry.indexOf(this.value) !== -1));
});
});
</code></pre>
<p><strong>template-reseller-getter.php</strong></p>
<pre><code><?php
$rd = $_POST['digwp_d'];
$rc = $_POST['digwp_e'];
$querystring = "cat=$rc&cat=$rd&posts_per_page=-1";
query_posts($querystring);
?>
<?php if (($rc == '-1') && ($rd == '-1')) { ?>
<table id="archives-table" class="table">
<tr>
<td style='text-align: center; font-size: 15px; padding: 5px;'><?php _e("Please choose from above.", "nalys-plugin") ?></td>
</tr>
</table>
<?php } else { ?>
<div id="archives-table">
<?php
$custom_args_empty_one = array(
'post_type' => 'reseller',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'reseller-country',
'field' => 'slug',
'terms' => $rc,
),
array(
'taxonomy' => 'reseller-department',
'field' => 'slug',
'terms' => $rd
)
)
);
$custom_args = array(
'post_type' => 'reseller',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'reseller-country',
'field' => 'slug',
'terms' => $rc,
),
array(
'taxonomy' => 'reseller-department',
'field' => 'slug',
'terms' => $rd
)
)
);
if ( $rc != '-1' && $rd == '-1' || $rc == '-1' && $rd != '-1' ) {
$custom_query = new WP_Query( $custom_args_empty_one );
} elseif ( $rc != '-1' && $rd != '-1' ){
$custom_query = new WP_Query( $custom_args );
}
if ($custom_query->have_posts()) :
$row = 0;
while ($custom_query->have_posts()) :
$custom_query->the_post();
$count = $custom_query->post_count;
if($count==1){
// Displaying data
echo '<div class="archives-table-reseller col-md-offset-4 col-md-4 col-sm-12 col-xs-12">';
the_title('<div class="reseller-title">', '</div>');
echo '<div class="reseller-address">'.get_post_meta($post->ID, '_address', true).'</div>';
echo '<div class="reseller-poscode">'.get_post_meta($post->ID, '_poscode', true).'</div>';
echo '<div class="reseller-telephone">Tel.'.get_post_meta($post->ID, '_telephone', true).'</div>';
echo '<div class="reseller-email"><a href="mailto:'.get_post_meta($post->ID, '_email', true).'">'.get_post_meta($post->ID, '_email', true).'</a></div>';
echo '<div class="reseller-email"><a href="http://'.get_post_meta($post->ID, '_website', true).'" target="_blank">'.get_post_meta($post->ID, '_website', true).'</a></div>';
echo "</div>";
}else{
// Displaying data
echo '<div class="archives-table-reseller col-md-4 col-sm-12 col-xs-12">';
the_title('<div class="reseller-title">', '</div>');
echo '<div class="reseller-address">'.get_post_meta($post->ID, '_address', true).'</div>';
echo '<div class="reseller-poscode">'.get_post_meta($post->ID, '_poscode', true).'</div>';
echo '<div class="reseller-telephone">Tel.'.get_post_meta($post->ID, '_telephone', true).'</div>';
echo '<div class="reseller-email"><a href="mailto:'.get_post_meta($post->ID, '_email', true).'">'.get_post_meta($post->ID, '_email', true).'</a></div>';
echo '<div class="reseller-email"><a href="http://'.get_post_meta($post->ID, '_website', true).'" target="_blank">'.get_post_meta($post->ID, '_website', true).'</a></div>';
echo "</div>";
}
endwhile; else:
echo "Nothing found.";
endif;
?>
</div>
<?php } ?>
</code></pre>
| [
{
"answer_id": 271089,
"author": "Ihor Vorotnov",
"author_id": 47359,
"author_profile": "https://wordpress.stackexchange.com/users/47359",
"pm_score": 4,
"selected": false,
"text": "<p>You can filter default rewrite rules and remove those for attachments:</p>\n\n<pre><code>function clean... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237816",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101256/"
] | I have build a custom post\_type with "Resellers" in order to enter my personal reseller items. The "Resellers" post have taxonomies like "Countries" and "Departmens".
I am running into a problem:
The first time that the page is displayed, nothing gets fetched from my custom post type taxonomies. If I click on one of my links, then the data get successfully updated. The issue is Country without "Département" assigned category (Allemagne for example) = The results are displayed but the "Département" drop-list should be hidden.
Can anyone tell me where have I done a mistake ?
**function.php**
```
if( !function_exists( 'reseller_department' ) ){
function reseller_department(){
$location = get_terms( 'reseller-department', array( 'parent' => 0 ) );
if( !empty($location) ){
foreach( $location as $term ){
if(isset($_GET['reseller_department']) ){
if($_GET['reseller_department'] == $term->slug ){
$selected = 'selected';
}else{
$selected = '';
}
}else{
$selected = '';
}
echo '<option value="'.$term->slug.'" '.$selected.'>'.$term->name.'</option>';
}
if(!isset($_GET['reseller_department']) || $_GET['reseller_department'] == '-1'){
echo '<option value="-1" selected>'.__( 'all departments', 'nalys-plugin' ).'</option>';
}else{
echo '<option value="-1">'.__( '…', 'nalys-plugin' ).'</option>';
}
}
}
}
if( !function_exists( 'reseller_country' ) ){
function reseller_country(){
$location = get_terms( 'reseller-country', array( 'parent' => 0 ) );
if( !empty($location) ){
foreach( $location as $term ){
if(isset($_GET['reseller_country']) ){
if($_GET['reseller_country'] == $term->slug ){
$selected = 'selected';
}else{
$selected = '';
}
}else{
$selected = '';
}
echo '<option value="'.$term->slug.'" '.$selected.'>'.$term->name.'</option>';
}
if(!isset($_GET['reseller_country']) || $_GET['reseller_country'] == '-1'){
echo '<option value="-1" selected>'.__( '...', 'nalys-plugin' ).'</option>';
}else{
echo '<option value="-1">'.__( '…', 'nalys-plugin' ).'</option>';
}
}
}
}
```
**archieve.js**
```
jQuery(document).ready(function($) {
$("#archive-wrapper").height($("#archive-pot").height());
$("#archive-browser select").change(function() {
$("#archive-pot")
.empty()
.html("<div style='text-align: center; padding: 30px;'>Loading...</div>");
var d = $("#reseller_department").val();
var e = $("#reseller_country").val();
$.ajax({
url: "/work/",
dataType: "html",
type: "POST",
data: {
"digwp_d" : d,
"digwp_e" : e
},
success: function(data) {
$("#archive-pot").html(data);
$("#archive-wrapper").animate({
height: $("#archives-table tr").length * 50
});
}
});
});
// get all data option value reseller country
var values = [];
var sel = document.getElementById('reseller_country');
for (var i=0, n=sel.options.length;i<n;i++) {
if (sel.options[i].value)
values.push(sel.options[i].value);
}
var jupe = '"' + values.join('","') + '"';
var dataOptionCountry = values;
dataOptionCountry.pop();
// console.log(dataOptionCountry);
$("#reseller_country").change(function () {
$("#reseller_department").prop("disabled", !(dataOptionCountry.indexOf(this.value) !== -1));
});
});
```
**template-reseller-getter.php**
```
<?php
$rd = $_POST['digwp_d'];
$rc = $_POST['digwp_e'];
$querystring = "cat=$rc&cat=$rd&posts_per_page=-1";
query_posts($querystring);
?>
<?php if (($rc == '-1') && ($rd == '-1')) { ?>
<table id="archives-table" class="table">
<tr>
<td style='text-align: center; font-size: 15px; padding: 5px;'><?php _e("Please choose from above.", "nalys-plugin") ?></td>
</tr>
</table>
<?php } else { ?>
<div id="archives-table">
<?php
$custom_args_empty_one = array(
'post_type' => 'reseller',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'reseller-country',
'field' => 'slug',
'terms' => $rc,
),
array(
'taxonomy' => 'reseller-department',
'field' => 'slug',
'terms' => $rd
)
)
);
$custom_args = array(
'post_type' => 'reseller',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'reseller-country',
'field' => 'slug',
'terms' => $rc,
),
array(
'taxonomy' => 'reseller-department',
'field' => 'slug',
'terms' => $rd
)
)
);
if ( $rc != '-1' && $rd == '-1' || $rc == '-1' && $rd != '-1' ) {
$custom_query = new WP_Query( $custom_args_empty_one );
} elseif ( $rc != '-1' && $rd != '-1' ){
$custom_query = new WP_Query( $custom_args );
}
if ($custom_query->have_posts()) :
$row = 0;
while ($custom_query->have_posts()) :
$custom_query->the_post();
$count = $custom_query->post_count;
if($count==1){
// Displaying data
echo '<div class="archives-table-reseller col-md-offset-4 col-md-4 col-sm-12 col-xs-12">';
the_title('<div class="reseller-title">', '</div>');
echo '<div class="reseller-address">'.get_post_meta($post->ID, '_address', true).'</div>';
echo '<div class="reseller-poscode">'.get_post_meta($post->ID, '_poscode', true).'</div>';
echo '<div class="reseller-telephone">Tel.'.get_post_meta($post->ID, '_telephone', true).'</div>';
echo '<div class="reseller-email"><a href="mailto:'.get_post_meta($post->ID, '_email', true).'">'.get_post_meta($post->ID, '_email', true).'</a></div>';
echo '<div class="reseller-email"><a href="http://'.get_post_meta($post->ID, '_website', true).'" target="_blank">'.get_post_meta($post->ID, '_website', true).'</a></div>';
echo "</div>";
}else{
// Displaying data
echo '<div class="archives-table-reseller col-md-4 col-sm-12 col-xs-12">';
the_title('<div class="reseller-title">', '</div>');
echo '<div class="reseller-address">'.get_post_meta($post->ID, '_address', true).'</div>';
echo '<div class="reseller-poscode">'.get_post_meta($post->ID, '_poscode', true).'</div>';
echo '<div class="reseller-telephone">Tel.'.get_post_meta($post->ID, '_telephone', true).'</div>';
echo '<div class="reseller-email"><a href="mailto:'.get_post_meta($post->ID, '_email', true).'">'.get_post_meta($post->ID, '_email', true).'</a></div>';
echo '<div class="reseller-email"><a href="http://'.get_post_meta($post->ID, '_website', true).'" target="_blank">'.get_post_meta($post->ID, '_website', true).'</a></div>';
echo "</div>";
}
endwhile; else:
echo "Nothing found.";
endif;
?>
</div>
<?php } ?>
``` | You can filter default rewrite rules and remove those for attachments:
```
function cleanup_default_rewrite_rules( $rules ) {
foreach ( $rules as $regex => $query ) {
if ( strpos( $regex, 'attachment' ) || strpos( $query, 'attachment' ) ) {
unset( $rules[ $regex ] );
}
}
return $rules;
}
add_filter( 'rewrite_rules_array', 'cleanup_default_rewrite_rules' );
```
Don't forget to re-save your permalinks once. WordPress will generate new rules without anything related to attachments.
Now, the attachment page URL gives 404. You can also add that redirect to prevent the 404 page, it's useless in this case. But I'm not sure how to catch the redirect - is\_attachment() will not work if the rewrite rules are removed.
**Update:**
WordPress will still offer the attachment page pretty URLs in media library and media insertion dialog. You can filter this as well:
```
function cleanup_attachment_link( $link ) {
return;
}
add_filter( 'attachment_link', 'cleanup_attachment_link' );
```
In this case, even when you insert your attachment into post ans select "Link to attachment page", the image will be inserted **without the link**. |
237,820 | <p>I retrieve information from database postmeta table.
I have 2 custom post type 'book' and 'author' I using metabox to connect them together. when user go to book custom post and adding new book. he must use check box metabox to determined which author write this book.</p>
<p>I have another page in my website which show author profile. in this page user can see books of author, my codes can save author for each book in database and read them perfectly and also can retrieve books of any author.</p>
<p>here is my problem I want to find each book feature image but when I use get_the_post_thumbnail it doesn't give me anything.</p>
<p>how can I fix this </p>
<p>I use var_dump to see each book information
here is the picture of it.
<a href="https://i.stack.imgur.com/5WQF3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5WQF3.png" alt="enter image description here"></a> </p>
<p>and here is my codes</p>
<pre><code><?php $args = array( 'post_type' => 'author');
$loop = new WP_Query( $args );
while ( have_posts() ) : the_post(); ?>
<div class="title-pack col-md-12 col-sm-12 col-xs-12">
<span class="line visible-sm-block"></span>
<span class="visible-sm-block tittle-style"><?php the_title(); ?></span>
</div>
<div class="row writer-crit">
<div class="writer-crit-box col-md-9 col-sm-8 col-xs-12">
<div class="col-md-11 col-sm-11 col-xs-12 pull-right">
<div class="writer-bio pull-right col-md-12 col-sm-12 col-xs-12">
<?php the_post_thumbnail('post-thumbnail',array('class' => 'pull-right')); ?>
<div class="writer-content-bio col-md-8 col-sm-8 col-xs-12 pull-right">
<h3><?php the_title(); ?></h3>
<?php the_content(); ?>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 pull-right">
<h3>کتابشناسی </h3>
<?php $ars = array( 'post_type' => 'book');
$loop = new WP_Query( $ars );
// for reading author which choose from cheak box in each book pages.
$post_id = get_the_ID();
$key = 'save-author-to-book';
$key2='save-trans-to-book';
// $vals=get_post_meta($post_id, $key2, true);
// $values = get_post_meta( $post_id, $key, true );
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
global $wpdb;
$x=(string) $post_id;
$sql='SELECT post_id FROM wp_postmeta WHERE meta_key = "save-author-to-book" AND meta_value LIKE "%'.$x.'%"';
$results = $wpdb->get_results( $sql, OBJECT );
foreach ($results as $result ) {
$array[]=$result->post_id;
}
foreach ($array as $arr) { ?>
<?php $autr_book=get_post($arr);
//var_dump($autr_book);?>
<li class="">
<a href="<?php echo $autr_book->guid;?>">
<div><?php get_the_post_thumbnail( $autr_book->ID ); ?></div>
<p><?php echo $autr_book->post_title; ?></p>
</a>
</li>
<?php } ?>
</div>
</div>
</div>
</div>
<?php endwhile; // End of the loop. ?>
<!-- ====================================
</code></pre>
| [
{
"answer_id": 237821,
"author": "WordPress Mechanic",
"author_id": 33660,
"author_profile": "https://wordpress.stackexchange.com/users/33660",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look here:</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/get_post_thum... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237820",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101035/"
] | I retrieve information from database postmeta table.
I have 2 custom post type 'book' and 'author' I using metabox to connect them together. when user go to book custom post and adding new book. he must use check box metabox to determined which author write this book.
I have another page in my website which show author profile. in this page user can see books of author, my codes can save author for each book in database and read them perfectly and also can retrieve books of any author.
here is my problem I want to find each book feature image but when I use get\_the\_post\_thumbnail it doesn't give me anything.
how can I fix this
I use var\_dump to see each book information
here is the picture of it.
[](https://i.stack.imgur.com/5WQF3.png)
and here is my codes
```
<?php $args = array( 'post_type' => 'author');
$loop = new WP_Query( $args );
while ( have_posts() ) : the_post(); ?>
<div class="title-pack col-md-12 col-sm-12 col-xs-12">
<span class="line visible-sm-block"></span>
<span class="visible-sm-block tittle-style"><?php the_title(); ?></span>
</div>
<div class="row writer-crit">
<div class="writer-crit-box col-md-9 col-sm-8 col-xs-12">
<div class="col-md-11 col-sm-11 col-xs-12 pull-right">
<div class="writer-bio pull-right col-md-12 col-sm-12 col-xs-12">
<?php the_post_thumbnail('post-thumbnail',array('class' => 'pull-right')); ?>
<div class="writer-content-bio col-md-8 col-sm-8 col-xs-12 pull-right">
<h3><?php the_title(); ?></h3>
<?php the_content(); ?>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 pull-right">
<h3>کتابشناسی </h3>
<?php $ars = array( 'post_type' => 'book');
$loop = new WP_Query( $ars );
// for reading author which choose from cheak box in each book pages.
$post_id = get_the_ID();
$key = 'save-author-to-book';
$key2='save-trans-to-book';
// $vals=get_post_meta($post_id, $key2, true);
// $values = get_post_meta( $post_id, $key, true );
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
global $wpdb;
$x=(string) $post_id;
$sql='SELECT post_id FROM wp_postmeta WHERE meta_key = "save-author-to-book" AND meta_value LIKE "%'.$x.'%"';
$results = $wpdb->get_results( $sql, OBJECT );
foreach ($results as $result ) {
$array[]=$result->post_id;
}
foreach ($array as $arr) { ?>
<?php $autr_book=get_post($arr);
//var_dump($autr_book);?>
<li class="">
<a href="<?php echo $autr_book->guid;?>">
<div><?php get_the_post_thumbnail( $autr_book->ID ); ?></div>
<p><?php echo $autr_book->post_title; ?></p>
</a>
</li>
<?php } ?>
</div>
</div>
</div>
</div>
<?php endwhile; // End of the loop. ?>
<!-- ====================================
``` | You use the function `get_the_post_thumbnail()` which returns a `string`. So you need to print that string with `echo` or use `the_post_thumbnail()` which echos itself. |
237,827 | <p>How we can get the complete cart details from the order id in woocommerce including the totals and subtotals etc.</p>
| [
{
"answer_id": 237831,
"author": "Annapurna",
"author_id": 98322,
"author_profile": "https://wordpress.stackexchange.com/users/98322",
"pm_score": 2,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code><?php\n global $woocommerce;\n $items = $woocommerce->cart->get_c... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237827",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83446/"
] | How we can get the complete cart details from the order id in woocommerce including the totals and subtotals etc. | Try this:
```
<?php
global $woocommerce;
$items = $woocommerce->cart->get_cart();
?>
``` |
237,833 | <p>I've got a partial called within <code>single.php</code> that looks like this:</p>
<pre><code><?php $userdata = get_userdata($post->post_author) ; ?>
<div class="entry-meta">
<span class="byline author vcard"><?= __('By', 'sage'); ?>
<a href="<?= get_author_posts_url(get_the_author_meta('ID')); ?>" rel="author" class="fn">
<?php echo ucfirst($userdata->user_nicename) ?>
</a>
</span>
</div>
</code></pre>
<p>Now, <code>$userdata</code> might be useful elsewhere within my single. So I'd like the variable and its value to be available globally within all templates that are included whenever my single is used.</p>
<p>So I cut out the first line: the creation of <code>$userdata</code> and put earlier in a 'parent' template that gets called earlier in the loop. </p>
<p>Alas, the variable was no longer avaiable to the partial. I tried a few other templates that are also called earlier in the loop. I got the same result: the variable wasn't available.</p>
<p>I thought about creating a function within <code>functions.php</code>. But I can think of a couple of reasons not to do this. First of all, why bother with an abstraction for <code>get_userdata()</code> when <code>get_userdata</code> already exists? This seems inelegant. </p>
| [
{
"answer_id": 237843,
"author": "WordPress Mechanic",
"author_id": 33660,
"author_profile": "https://wordpress.stackexchange.com/users/33660",
"pm_score": 0,
"selected": false,
"text": "<p><strong>There are two solutions:</strong></p>\n\n<p><strong>1)</strong> Use a variable like this\n... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237833",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51378/"
] | I've got a partial called within `single.php` that looks like this:
```
<?php $userdata = get_userdata($post->post_author) ; ?>
<div class="entry-meta">
<span class="byline author vcard"><?= __('By', 'sage'); ?>
<a href="<?= get_author_posts_url(get_the_author_meta('ID')); ?>" rel="author" class="fn">
<?php echo ucfirst($userdata->user_nicename) ?>
</a>
</span>
</div>
```
Now, `$userdata` might be useful elsewhere within my single. So I'd like the variable and its value to be available globally within all templates that are included whenever my single is used.
So I cut out the first line: the creation of `$userdata` and put earlier in a 'parent' template that gets called earlier in the loop.
Alas, the variable was no longer avaiable to the partial. I tried a few other templates that are also called earlier in the loop. I got the same result: the variable wasn't available.
I thought about creating a function within `functions.php`. But I can think of a couple of reasons not to do this. First of all, why bother with an abstraction for `get_userdata()` when `get_userdata` already exists? This seems inelegant. | WordPress caches the user information. There's really no problem just to call `get_userdata` every time you need it. The only thing you are doing by transfering it to a variable `$userdata` is have WP fetch it from another place in the memory.
Note: read [this post](https://wordpress.stackexchange.com/questions/176804/passing-a-variable-to-get-template-part) for a more general dealing with passing variables to partials. |
237,834 | <p>I set post per page from setting>maximum post per page to 20. I have 2 different custom post types 'book' and 'author' for archives of each of them. I want to load different number of post in page. I want to load 20 book per page in book archive and 5 post in author archive in each page. I also use WP-PageNavi plugin.</p>
<p>Here is my code</p>
<pre><code><?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array( 'post_type' => 'Author','paged' => $paged,'posts_per_page' =>5 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php the_permalink(); ?>" class="writer-link col-md-12 col-sm-12 col-xs-12">
<div class="writer-row1 col-md-12 col-sm-12 col-xs-12">
<div class="col-md-2 col-sm-3 col-xs-12 image-right">
<?php the_post_thumbnail('post-thumbnail',array('class' => 'img-responsive')); ?>
</div>
<div class="col-md-10 col-xs-12 col-sm-9 col-xs-12 pull-right writer-content">
<h3><?php the_title(); ?></h3>
<h4><?php the_field('auth-trans'); ?></h4>
<?php if ( get_field('writer-bio') ) {
echo '<p>'.get_field('writer-bio').'</p>';} ?>
<span>...</span>
</div>
</div>
</a>
<?php endwhile; // End of the loop. ?>
<div class="wp-pagenavi row">
<div id="wp_page_numbers text-center col-sm-6 center-margin">
<ul>
<li class="active_page text-center"><?php if(function_exists('wp_pagenavi')) { wp_pagenavi(array( 'query' => $loop )); } ?></li>
</ul>
</div>
</div>
</code></pre>
<p>No problem with book archive: it loads 20 posts. But I don't know how I can make author page to load just 5 post per page and after it has loaded 5 first posts it is going to next page.</p>
| [
{
"answer_id": 237847,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>You will have to make the query arguments dependend on the type of archive you are generating (which WP already ... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101035/"
] | I set post per page from setting>maximum post per page to 20. I have 2 different custom post types 'book' and 'author' for archives of each of them. I want to load different number of post in page. I want to load 20 book per page in book archive and 5 post in author archive in each page. I also use WP-PageNavi plugin.
Here is my code
```
<?php
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$args = array( 'post_type' => 'Author','paged' => $paged,'posts_per_page' =>5 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<a href="<?php the_permalink(); ?>" class="writer-link col-md-12 col-sm-12 col-xs-12">
<div class="writer-row1 col-md-12 col-sm-12 col-xs-12">
<div class="col-md-2 col-sm-3 col-xs-12 image-right">
<?php the_post_thumbnail('post-thumbnail',array('class' => 'img-responsive')); ?>
</div>
<div class="col-md-10 col-xs-12 col-sm-9 col-xs-12 pull-right writer-content">
<h3><?php the_title(); ?></h3>
<h4><?php the_field('auth-trans'); ?></h4>
<?php if ( get_field('writer-bio') ) {
echo '<p>'.get_field('writer-bio').'</p>';} ?>
<span>...</span>
</div>
</div>
</a>
<?php endwhile; // End of the loop. ?>
<div class="wp-pagenavi row">
<div id="wp_page_numbers text-center col-sm-6 center-margin">
<ul>
<li class="active_page text-center"><?php if(function_exists('wp_pagenavi')) { wp_pagenavi(array( 'query' => $loop )); } ?></li>
</ul>
</div>
</div>
```
No problem with book archive: it loads 20 posts. But I don't know how I can make author page to load just 5 post per page and after it has loaded 5 first posts it is going to next page. | add below code in functions.php file , here "event" is custom post type (change it as per your post type) , so here it will display 6 post on events list page , also you need to copy default archive.php file and copy and create new archive-event.php (replace event with your post type).
```
function custom_type_archive_display($query) {
if (is_post_type_archive('event')) {
$query->set('posts_per_page',6);
$query->set('orderby', 'date' );
$query->set('order', 'DESC' );
return;
}
}
add_action('pre_get_posts', 'custom_type_archive_display');
```
Hope this Helps :)
More detail how to list custom post on custom page refer this link [Custom Posts on Different Pages](https://wordpress.stackexchange.com/questions/175120/custom-posts-on-different-pages/270656#270656) |
237,854 | <p>I have problem with <code>wp_localize_script</code>, That I cannot get <strong>boolean</strong> and <strong>int</strong> as variable</p>
<pre><code>wp_enqueue_script( 'helloworld' , 'helloworld.js', false, '1.0.0', true);
$site_config = array();
$site_config['boo'] = (bool)true;
$site_config['number'] = (int)1;
wp_localize_script( 'helloworld' , 'site_config' , $site_config );
</code></pre>
<p><strong>Why I getting :</strong></p>
<pre><code>var site_config = {"boo":"1","number":"1"};
</code></pre>
<p><strong>Why not :</strong></p>
<pre><code>var site_config = {"boo":true,"number":1};
</code></pre>
<ul>
<li>Wordpress 4.6 <em>(latest)</em></li>
<li>PHP 5.6.10</li>
</ul>
<p>Does not it fixed ? <a href="https://core.trac.wordpress.org/ticket/25280" rel="nofollow">https://core.trac.wordpress.org/ticket/25280</a> , I do anything wrong or missing something ?</p>
| [
{
"answer_id": 237856,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<h2><em>Why</em> part:</h2>\n\n<p>The <em>Why</em> part can be found within the <code>WP_Scripts::localize()</co... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6332/"
] | I have problem with `wp_localize_script`, That I cannot get **boolean** and **int** as variable
```
wp_enqueue_script( 'helloworld' , 'helloworld.js', false, '1.0.0', true);
$site_config = array();
$site_config['boo'] = (bool)true;
$site_config['number'] = (int)1;
wp_localize_script( 'helloworld' , 'site_config' , $site_config );
```
**Why I getting :**
```
var site_config = {"boo":"1","number":"1"};
```
**Why not :**
```
var site_config = {"boo":true,"number":1};
```
* Wordpress 4.6 *(latest)*
* PHP 5.6.10
Does not it fixed ? <https://core.trac.wordpress.org/ticket/25280> , I do anything wrong or missing something ? | **I just do something like this so long :**
```
wp_add_inline_script('helloworld','var site_config ='.json_encode($site_config));
``` |
237,878 | <p>Sometimes I want to change a post a little bit, but the post was already published on my blog. The change concerns adding/removing tags or rewriting the title of the post (just to correct a misspelled word). All the things can be done using the admin panel by pressing "quick edit".</p>
<p>Unfortunately, the action updates the "modified time". I'm using the "modified time" so people would know whether a post was modified or not. But I want to disable the modified time updates in the case when I just make some small changes like to ones described above. Is there a way to do it?</p>
| [
{
"answer_id": 237889,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like you're only displaying this information on the single post view and not making any searches fo... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70882/"
] | Sometimes I want to change a post a little bit, but the post was already published on my blog. The change concerns adding/removing tags or rewriting the title of the post (just to correct a misspelled word). All the things can be done using the admin panel by pressing "quick edit".
Unfortunately, the action updates the "modified time". I'm using the "modified time" so people would know whether a post was modified or not. But I want to disable the modified time updates in the case when I just make some small changes like to ones described above. Is there a way to do it? | The question of how to customize which post data gets updated has been answered [elsewhere on StackExchange](https://wordpress.stackexchange.com/questions/35931/how-can-i-edit-post-data-before-it-is-saved).
Here is a specific example of how to stop the modified date from being updated:
```
function stop_modified_date_update( $new, $old ) {
$new['post_modified'] = $old['post_modified'];
$new['post_modified_gmt'] = $old['post_modified_gmt'];
return $new;
}
add_filter( 'wp_insert_post_data', 'stop_modified_date_update', 10, 2 );
// do stuff that updates post(s) here
remove_filter( 'wp_insert_post_data', 'stop_modified_date_update', 10, 2 );
```
NB: It is extremely important to remove the filter when you're done with your special tasks unless you really want the modified date to never update anywhere on the site.
Happy coding! |
237,879 | <p>Is it possible to override Javascript in a plugin with a child theme?</p>
<p>Specifically I'm trying to override a portion of a WooCommerce product page - I would like to get rid of the tabbed content areas, and instead have all of the content visible with the "tabs" then being anchor links down the page.</p>
<p>I've figured out how to do that on a local install by deleting a portion of Javascript within the WooCommerce plugin files - but that's obviously not a workable solution longterm.</p>
<p>I would like to essentially dequeue the Javascript in the plugin, and enqueue my own file with the unneeded portion removed.</p>
<p>This is the bit of code I need to be rid of, if there's another way to go about overriding it?</p>
<pre><code>.on( 'click', '.wc-tabs li a, ul.tabs li a', function( e ) {
e.preventDefault();
var $tab = $( this );
var $tabs_wrapper = $tab.closest( '.wc-tabs-wrapper, .woocommerce-tabs' );
var $tabs = $tabs_wrapper.find( '.wc-tabs, ul.tabs' );
$tabs.find( 'li' ).removeClass( 'active' );
$tabs_wrapper.find( '.wc-tab, .panel:not(.panel .panel)' ).hide();
$tab.closest( 'li' ).addClass( 'active' );
$tabs_wrapper.find( $tab.attr( 'href' ) ).show();
})
</code></pre>
| [
{
"answer_id": 237881,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>You can disable this portion of JavaScript code with this code : </p>\n\n<pre><code>$( 'body' ).off( 'click', '.w... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237879",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85805/"
] | Is it possible to override Javascript in a plugin with a child theme?
Specifically I'm trying to override a portion of a WooCommerce product page - I would like to get rid of the tabbed content areas, and instead have all of the content visible with the "tabs" then being anchor links down the page.
I've figured out how to do that on a local install by deleting a portion of Javascript within the WooCommerce plugin files - but that's obviously not a workable solution longterm.
I would like to essentially dequeue the Javascript in the plugin, and enqueue my own file with the unneeded portion removed.
This is the bit of code I need to be rid of, if there's another way to go about overriding it?
```
.on( 'click', '.wc-tabs li a, ul.tabs li a', function( e ) {
e.preventDefault();
var $tab = $( this );
var $tabs_wrapper = $tab.closest( '.wc-tabs-wrapper, .woocommerce-tabs' );
var $tabs = $tabs_wrapper.find( '.wc-tabs, ul.tabs' );
$tabs.find( 'li' ).removeClass( 'active' );
$tabs_wrapper.find( '.wc-tab, .panel:not(.panel .panel)' ).hide();
$tab.closest( 'li' ).addClass( 'active' );
$tabs_wrapper.find( $tab.attr( 'href' ) ).show();
})
``` | You can disable this portion of JavaScript code with this code :
```
$( 'body' ).off( 'click', '.wc-tabs li a, ul.tabs li a');
```
`.off(` detach the listeners : <http://api.jquery.com/off/> |
237,882 | <p>I'm getting a feed error of 'XML parsing error: :[line number]:0: junk after document element'.</p>
<p>Although such errors often seem to be from unwanted code injections, mine is showing 'Cannot modify header information - headers already sent by'... which I've previously had with unwanted white space.</p>
<p>'Warning: Cannot modify header information - headers already sent by (output started at ...path to... /wp-includes/feed-rss2.php:11) in ...path to custom theme... /feed-rss2.php on line 3<.'</p>
<p>The two files noted in the error, are identical to those in other installs which don't have this error - which seems to trigger at the end of the last-but-one item in the feed.</p>
| [
{
"answer_id": 237881,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>You can disable this portion of JavaScript code with this code : </p>\n\n<pre><code>$( 'body' ).off( 'click', '.w... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63350/"
] | I'm getting a feed error of 'XML parsing error: :[line number]:0: junk after document element'.
Although such errors often seem to be from unwanted code injections, mine is showing 'Cannot modify header information - headers already sent by'... which I've previously had with unwanted white space.
'Warning: Cannot modify header information - headers already sent by (output started at ...path to... /wp-includes/feed-rss2.php:11) in ...path to custom theme... /feed-rss2.php on line 3<.'
The two files noted in the error, are identical to those in other installs which don't have this error - which seems to trigger at the end of the last-but-one item in the feed. | You can disable this portion of JavaScript code with this code :
```
$( 'body' ).off( 'click', '.wc-tabs li a, ul.tabs li a');
```
`.off(` detach the listeners : <http://api.jquery.com/off/> |
237,886 | <p><strong>I know it's not supposed to work like this and that InstantWP is made for testing and not for an actual website</strong>, but I didn't know it when I started out and after two months of work I just can't throw it all away and start over.</p>
<p><em>Is there any way to transfer what I made on a ftp server ?</em></p>
<p>I'm a newbie, so please be kind and detailed :)</p>
| [
{
"answer_id": 237881,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 1,
"selected": false,
"text": "<p>You can disable this portion of JavaScript code with this code : </p>\n\n<pre><code>$( 'body' ).off( 'click', '.w... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102015/"
] | **I know it's not supposed to work like this and that InstantWP is made for testing and not for an actual website**, but I didn't know it when I started out and after two months of work I just can't throw it all away and start over.
*Is there any way to transfer what I made on a ftp server ?*
I'm a newbie, so please be kind and detailed :) | You can disable this portion of JavaScript code with this code :
```
$( 'body' ).off( 'click', '.wc-tabs li a, ul.tabs li a');
```
`.off(` detach the listeners : <http://api.jquery.com/off/> |
237,903 | <p>I've got a Layer 7 Load Balancer setup using HAProxy for WordPress Multisite.</p>
<p>I'm looking to have anything related to the WordPress backend to be served from a specific group of servers (A/K/A anything in <code>/wp-admin/</code>) while serving the frontend of the WordPress websites from another group of servers.</p>
<p>Do I need to adjust something in <code>wp-config.php</code> to change cookie names so that they include the server ID? or check for the server ID in the WordPress cookie? I feel like problems #1 and #2 are cookie related. I have no idea why #3 is happening. My servers aren't lagging at all, and should be responding plenty fast.</p>
<p><strong>With my current configuration I'm facing a few problems here:</strong></p>
<ol>
<li><p>It does indeed appear to be connecting me to the appropriate admin server. However, after a while in the dashboard. The WordPress
login form pops up asking me to re-login again.</p></li>
<li><p>Most admin pages work just fine however once in a while, again, same
as #1, the WordPress login for pops up and asks me to login again.</p></li>
<li><p>Every now in then I get a "504 Gateway Time-out - The server didn't
respond in time."</p></li>
</ol>
<p><strong>Here's what my configuration looks like:</strong></p>
<pre><code>defaults
log global
mode http
option httplog
option dontlognull
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
retries 3
option redispatch
maxconn 2000
timeout connect 5000
timeout check 5000
timeout client 30000
timeout server 30000
frontend http-in
bind *:80
option httplog
option http-server-close
acl has_domain hdr(host) -m found
acl has_www hdr_beg(host) -i www.
use_backend live_servers if has_domain has_www
acl has_admin path_beg /wp-admin
acl has_login path_beg /wp-login.php
acl has_custom_login path_beg /manage
use_backend admin_servers if has_admin or has_login or has_custom_login
default_backend live_servers
backend live_servers
mode http
stats enable
stats uri /haproxy?stats
balance roundrobin
option httpclose
option forwardfor
cookie SERVERID insert indirect nocache
server s1 1.1.1.1:80 check cookie s1
server s2 2.2.2.2:80 check cookie s2
backend admin_servers
mode http
stats enable
stats uri /haproxy?stats
balance roundrobin
option httpclose
option forwardfor
cookie SERVERID insert indirect nocache
server s1 1.1.1.1:80 check cookie s1
</code></pre>
<p>I'm willing to provide a pretty hefty bounty for this. If there's any settings which I'm missing or you think you could improve upon my configuration, please provide a full configuration including all appropriate settings in your answer.</p>
<p>Edit: I am currently using HAProxy 1.6.x and willing to upgrade to latest version if that's what it takes to get a valid solution.</p>
| [
{
"answer_id": 238745,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Most of your question seem to be server related and would be off topic here, but here's my five cents on the Wor... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237903",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9579/"
] | I've got a Layer 7 Load Balancer setup using HAProxy for WordPress Multisite.
I'm looking to have anything related to the WordPress backend to be served from a specific group of servers (A/K/A anything in `/wp-admin/`) while serving the frontend of the WordPress websites from another group of servers.
Do I need to adjust something in `wp-config.php` to change cookie names so that they include the server ID? or check for the server ID in the WordPress cookie? I feel like problems #1 and #2 are cookie related. I have no idea why #3 is happening. My servers aren't lagging at all, and should be responding plenty fast.
**With my current configuration I'm facing a few problems here:**
1. It does indeed appear to be connecting me to the appropriate admin server. However, after a while in the dashboard. The WordPress
login form pops up asking me to re-login again.
2. Most admin pages work just fine however once in a while, again, same
as #1, the WordPress login for pops up and asks me to login again.
3. Every now in then I get a "504 Gateway Time-out - The server didn't
respond in time."
**Here's what my configuration looks like:**
```
defaults
log global
mode http
option httplog
option dontlognull
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
retries 3
option redispatch
maxconn 2000
timeout connect 5000
timeout check 5000
timeout client 30000
timeout server 30000
frontend http-in
bind *:80
option httplog
option http-server-close
acl has_domain hdr(host) -m found
acl has_www hdr_beg(host) -i www.
use_backend live_servers if has_domain has_www
acl has_admin path_beg /wp-admin
acl has_login path_beg /wp-login.php
acl has_custom_login path_beg /manage
use_backend admin_servers if has_admin or has_login or has_custom_login
default_backend live_servers
backend live_servers
mode http
stats enable
stats uri /haproxy?stats
balance roundrobin
option httpclose
option forwardfor
cookie SERVERID insert indirect nocache
server s1 1.1.1.1:80 check cookie s1
server s2 2.2.2.2:80 check cookie s2
backend admin_servers
mode http
stats enable
stats uri /haproxy?stats
balance roundrobin
option httpclose
option forwardfor
cookie SERVERID insert indirect nocache
server s1 1.1.1.1:80 check cookie s1
```
I'm willing to provide a pretty hefty bounty for this. If there's any settings which I'm missing or you think you could improve upon my configuration, please provide a full configuration including all appropriate settings in your answer.
Edit: I am currently using HAProxy 1.6.x and willing to upgrade to latest version if that's what it takes to get a valid solution. | **The problem #1 & #2**:
Don't know why you need to add and validate extra cookies, but for me, it's simple and quite straight forward:
This is what I have tried on vagrant boxes and with default WordPress structure:
**1**. Prepare 6 separate servers
* `111.111.1.10` - MySQL server
* `111.111.1.11` - HAProxy server
* `111.111.1.12` & `111.111.1.13` - for admin URLs
* `111.111.1.14` & `111.111.1.15` - for non-admin URLs
HAProxy (v1.6) configurations:
```
defaults
log global
mode http
option httplog
option forwardfor
option dontlognull
option http-server-close
timeout connect 5000
timeout client 50000
timeout server 50000
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
frontend http-revolver
bind 111.111.1.11:80
acl url_is_wp_admin path_beg /wp-admin /wp-login.php /manage
use_backend admin-servers if url_is_wp_admin
default_backend public-servers
backend public-servers
server s1 111.111.1.12:80 check
server s2 111.111.1.13:80 check
backend admin-servers
server s3 111.111.1.14:80 check
server s4 111.111.1.15:80 check
listen stats
bind 111.111.1.11:1984
stats enable
stats scope http-revolver
stats scope public-servers
stats scope admin-servers
stats uri /
stats realm Haproxy\ Statistics
stats auth user:password
```
**2**. Use `wpms.dev` as a demo domain and point it to `111.111.1.11` in `/etc/hosts` of host machine.
**3**. Install a base box with `ubuntu/trusty64` (LAMP stack + WP multisite) on server `111.111.1.12`.
The most important step to avoid the problem #1 & #2 is, **because some WordPress cookies depend on paths**, we must make sure these constants are consistent in all servers:
```
define('WP_HOME', 'http://wpms.dev');
define('WP_SITEURL', 'http://wpms.dev');
define('DOMAIN_CURRENT_SITE', 'wpms.dev');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
```
To do it, we just need to add it to `wp-config.php` in this base box.
**4**. Package the base box and duplicate it on other servers: `111.111.1.13`, `111.111.1.14` and `111.111.1.15`. Now `vagrant up` for all servers and check it out.
If you have ssh authentication failure, you must point `config.ssh.private_key_path` to the `private_key` of the base box in `Vagrantfile`s of the duplicated boxes.
**The problem #3** is too abroad and may be off-topic here. It can be storage error, server config error... You should ask it on a appropriate network site. :-) |
237,913 | <p>I need to override the 404 code for a very specific scenario and it's not yet fully working.</p>
<p>I am linking day archives with <code>rel=prev/next</code>, and the chain is supposed to be intact start-to-end. For this reason, at least one post needs to be published everyday, best right at midnight. This should not be a problem editorially, with at least 10 posts being expected even on a slow news day.</p>
<p>However, accidents may happen - like downtime or unwarranted deletions or whatnot. Even in these cases, things should be repaired from the publishing end as soon as noticed (with at least one post forth/backdated to cover for the empty day).</p>
<p>Still, I wouldn't want the prev/next chain to ever be broken, so I'm thinking this as the ultimate fallback - ideally never triggered.</p>
<p>I have added the following to the functions.php template:</p>
<pre><code>add_action( 'template_redirect', 'empty_day', 0 );
function empty_day() {
global $wp_query;
if ($wp_query->post_count == 0 && $wp_query->query['day'] ) {
status_header( '200' );
$wp_query->is_404 = false;
$wp_query->is_day = true;
$wp_query->is_date = true;
$wp_query->is_archive = true;
}
}
</code></pre>
<p>It works nicely redirecting the empty page to the archive template, prev/next tags in place.</p>
<p>However, functions stop working outside the loop completely (no return), so I can't <a href="https://codex.wordpress.org/Function_Reference/get_the_time" rel="nofollow noreferrer"><code>get_the_time</code></a> nor <a href="https://codex.wordpress.org/Function_Reference/get_the_date" rel="nofollow noreferrer"><code>get_the_date</code></a> to output anything.</p>
<p>I already tried the solutions suggested <a href="https://wordpress.stackexchange.com/questions/104991/preventing-404-error-on-empty-date-archive">here</a> or <a href="https://wordpress.org/support/topic/empty-archives-returning-404" rel="nofollow noreferrer">here</a>, but they still fail to get the date with the <code>template_redirect</code> filter or redirect the template altogether with <code>404_template</code>.</p>
<p>Any Idea on how to have them working again?</p>
| [
{
"answer_id": 238745,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Most of your question seem to be server related and would be off topic here, but here's my five cents on the Wor... | 2016/09/01 | [
"https://wordpress.stackexchange.com/questions/237913",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70333/"
] | I need to override the 404 code for a very specific scenario and it's not yet fully working.
I am linking day archives with `rel=prev/next`, and the chain is supposed to be intact start-to-end. For this reason, at least one post needs to be published everyday, best right at midnight. This should not be a problem editorially, with at least 10 posts being expected even on a slow news day.
However, accidents may happen - like downtime or unwarranted deletions or whatnot. Even in these cases, things should be repaired from the publishing end as soon as noticed (with at least one post forth/backdated to cover for the empty day).
Still, I wouldn't want the prev/next chain to ever be broken, so I'm thinking this as the ultimate fallback - ideally never triggered.
I have added the following to the functions.php template:
```
add_action( 'template_redirect', 'empty_day', 0 );
function empty_day() {
global $wp_query;
if ($wp_query->post_count == 0 && $wp_query->query['day'] ) {
status_header( '200' );
$wp_query->is_404 = false;
$wp_query->is_day = true;
$wp_query->is_date = true;
$wp_query->is_archive = true;
}
}
```
It works nicely redirecting the empty page to the archive template, prev/next tags in place.
However, functions stop working outside the loop completely (no return), so I can't [`get_the_time`](https://codex.wordpress.org/Function_Reference/get_the_time) nor [`get_the_date`](https://codex.wordpress.org/Function_Reference/get_the_date) to output anything.
I already tried the solutions suggested [here](https://wordpress.stackexchange.com/questions/104991/preventing-404-error-on-empty-date-archive) or [here](https://wordpress.org/support/topic/empty-archives-returning-404), but they still fail to get the date with the `template_redirect` filter or redirect the template altogether with `404_template`.
Any Idea on how to have them working again? | **The problem #1 & #2**:
Don't know why you need to add and validate extra cookies, but for me, it's simple and quite straight forward:
This is what I have tried on vagrant boxes and with default WordPress structure:
**1**. Prepare 6 separate servers
* `111.111.1.10` - MySQL server
* `111.111.1.11` - HAProxy server
* `111.111.1.12` & `111.111.1.13` - for admin URLs
* `111.111.1.14` & `111.111.1.15` - for non-admin URLs
HAProxy (v1.6) configurations:
```
defaults
log global
mode http
option httplog
option forwardfor
option dontlognull
option http-server-close
timeout connect 5000
timeout client 50000
timeout server 50000
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
frontend http-revolver
bind 111.111.1.11:80
acl url_is_wp_admin path_beg /wp-admin /wp-login.php /manage
use_backend admin-servers if url_is_wp_admin
default_backend public-servers
backend public-servers
server s1 111.111.1.12:80 check
server s2 111.111.1.13:80 check
backend admin-servers
server s3 111.111.1.14:80 check
server s4 111.111.1.15:80 check
listen stats
bind 111.111.1.11:1984
stats enable
stats scope http-revolver
stats scope public-servers
stats scope admin-servers
stats uri /
stats realm Haproxy\ Statistics
stats auth user:password
```
**2**. Use `wpms.dev` as a demo domain and point it to `111.111.1.11` in `/etc/hosts` of host machine.
**3**. Install a base box with `ubuntu/trusty64` (LAMP stack + WP multisite) on server `111.111.1.12`.
The most important step to avoid the problem #1 & #2 is, **because some WordPress cookies depend on paths**, we must make sure these constants are consistent in all servers:
```
define('WP_HOME', 'http://wpms.dev');
define('WP_SITEURL', 'http://wpms.dev');
define('DOMAIN_CURRENT_SITE', 'wpms.dev');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
```
To do it, we just need to add it to `wp-config.php` in this base box.
**4**. Package the base box and duplicate it on other servers: `111.111.1.13`, `111.111.1.14` and `111.111.1.15`. Now `vagrant up` for all servers and check it out.
If you have ssh authentication failure, you must point `config.ssh.private_key_path` to the `private_key` of the base box in `Vagrantfile`s of the duplicated boxes.
**The problem #3** is too abroad and may be off-topic here. It can be storage error, server config error... You should ask it on a appropriate network site. :-) |
237,947 | <p>My organization has a website powered by wordpress. We are using pagebuilder to design pages. We also have some assets (pdf files, ppts) etc. Currently everyone can access these files. </p>
<p>I need to modify them so that there is some access control. So the first suggestion to provide the access control was “register” each user that wants to access the files. Based on the type of user (normal, HR, Finance etc) each of them can have access to a specific set of files. </p>
<p>Could anyone suggest how the above can be done. </p>
| [
{
"answer_id": 238745,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>Most of your question seem to be server related and would be off topic here, but here's my five cents on the Wor... | 2016/09/02 | [
"https://wordpress.stackexchange.com/questions/237947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102068/"
] | My organization has a website powered by wordpress. We are using pagebuilder to design pages. We also have some assets (pdf files, ppts) etc. Currently everyone can access these files.
I need to modify them so that there is some access control. So the first suggestion to provide the access control was “register” each user that wants to access the files. Based on the type of user (normal, HR, Finance etc) each of them can have access to a specific set of files.
Could anyone suggest how the above can be done. | **The problem #1 & #2**:
Don't know why you need to add and validate extra cookies, but for me, it's simple and quite straight forward:
This is what I have tried on vagrant boxes and with default WordPress structure:
**1**. Prepare 6 separate servers
* `111.111.1.10` - MySQL server
* `111.111.1.11` - HAProxy server
* `111.111.1.12` & `111.111.1.13` - for admin URLs
* `111.111.1.14` & `111.111.1.15` - for non-admin URLs
HAProxy (v1.6) configurations:
```
defaults
log global
mode http
option httplog
option forwardfor
option dontlognull
option http-server-close
timeout connect 5000
timeout client 50000
timeout server 50000
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
frontend http-revolver
bind 111.111.1.11:80
acl url_is_wp_admin path_beg /wp-admin /wp-login.php /manage
use_backend admin-servers if url_is_wp_admin
default_backend public-servers
backend public-servers
server s1 111.111.1.12:80 check
server s2 111.111.1.13:80 check
backend admin-servers
server s3 111.111.1.14:80 check
server s4 111.111.1.15:80 check
listen stats
bind 111.111.1.11:1984
stats enable
stats scope http-revolver
stats scope public-servers
stats scope admin-servers
stats uri /
stats realm Haproxy\ Statistics
stats auth user:password
```
**2**. Use `wpms.dev` as a demo domain and point it to `111.111.1.11` in `/etc/hosts` of host machine.
**3**. Install a base box with `ubuntu/trusty64` (LAMP stack + WP multisite) on server `111.111.1.12`.
The most important step to avoid the problem #1 & #2 is, **because some WordPress cookies depend on paths**, we must make sure these constants are consistent in all servers:
```
define('WP_HOME', 'http://wpms.dev');
define('WP_SITEURL', 'http://wpms.dev');
define('DOMAIN_CURRENT_SITE', 'wpms.dev');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
```
To do it, we just need to add it to `wp-config.php` in this base box.
**4**. Package the base box and duplicate it on other servers: `111.111.1.13`, `111.111.1.14` and `111.111.1.15`. Now `vagrant up` for all servers and check it out.
If you have ssh authentication failure, you must point `config.ssh.private_key_path` to the `private_key` of the base box in `Vagrantfile`s of the duplicated boxes.
**The problem #3** is too abroad and may be off-topic here. It can be storage error, server config error... You should ask it on a appropriate network site. :-) |
237,957 | <p>I am trying to fetch a post based on the following meta keys.</p>
<ul>
<li><code>post_code</code> with <code>432C</code></li>
<li><code>location</code> with <code>XYZ</code>
Both belong to a CPT. I'm trying to fetch the Post with both these meta_values. </li>
</ul>
<p>I Don't Want an OR relation, I want a AND relation, I have tried several <code>WP_Query</code> objects and still haven't found a solution after hours of looking. </p>
| [
{
"answer_id": 237958,
"author": "Manthan Dave",
"author_id": 83209,
"author_profile": "https://wordpress.stackexchange.com/users/83209",
"pm_score": -1,
"selected": false,
"text": "<p>Tried below object parametes</p>\n\n<pre><code>array(\n 'key' => 'post_code',\n ... | 2016/09/02 | [
"https://wordpress.stackexchange.com/questions/237957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89206/"
] | I am trying to fetch a post based on the following meta keys.
* `post_code` with `432C`
* `location` with `XYZ`
Both belong to a CPT. I'm trying to fetch the Post with both these meta\_values.
I Don't Want an OR relation, I want a AND relation, I have tried several `WP_Query` objects and still haven't found a solution after hours of looking. | **SOLUTION**
The Solution Accepted below worked, however, I wanted to know how is it working?
This is how it's working
```
SELECT * FROM wp_posts p, wp_postmeta m1, wp_postmeta m2
WHERE p.ID = m1.post_id and p.ID = m2.post_id
AND m1.meta_key = 'key1' AND m1.meta_value = 'value1'
AND m2.meta_key = 'key2' AND m2.meta_value = 'value2'
AND p.post_type = 'cpt' AND p.post_status = 'published'
``` |
237,986 | <p>I have three files: <code>submit.php</code> (a page), <code>validation.php</code>, <code>script.php</code></p>
<p>I am trying to use the fields as a front end submission area via the <code>wp_insert_post()</code> function.</p>
<p>However, I don't know exactly where to put the function, as where I try either is before the <code>validation.php</code> file or if I put it in that file it causes an error since it can't pass wordpress functions.</p>
<p>I have tried playing with the <code>success</code> in the <code>$.ajax</code> but since the <code>die()</code> functions all result in it being successful can't trigger a create post.</p>
<p>Does anyone have a better solution?</p>
<p>In the <code>submit.php</code> I have a form:</p>
<pre><code><div class="" id="response"></div>
<form id="form_ticket_submit" method="post">
<label for="form_ticket_subject">Subject of issue</label>
<input id="form_ticket_subject" name="form_ticket_subject" type="text">
<label for="form_ticket_content">Post</label>
<textarea id="form_ticket_content" name="form_ticket_content"></textarea>
<label for="form_ticket_tax_stage">Select Stage</label>
<select id="form_ticket_tax_stage" name="form_ticket_tax_stage">
<option value="">Select one</option>
<?php foreach ($form_ticket_tax_cat_stage as $form_cat_stage) { echo '<option value="' . $form_cat_stage->slug . '">'. $form_cat_stage->name . '</option>'; } ?>
</select>
<input hidden="hidden" id="form_ticket_meta_date" name="form_ticket_meta_date" type="text" readonly="readonly" value="<?php echo get_date_from_gmt( date( 'Y-m-d H:i:s' ), 'jS \of F, Y H:i:s' ); ?>">
<input hidden="hidden" id="form_ticket_meta_user_name" name="form_ticket_meta_user_name" type="text" readonly="readonly" value="<?php echo $form_ticket_current_user_name; ?>">
<input hidden="hidden" id="form_ticket_meta_user_email" name="form_ticket_meta_user_email" type="text" readonly="readonly" value="<?php echo $form_ticket_current_user_email; ?>">
<input name="submit" type="submit" value="Submit Ticket" />
</form>
</code></pre>
<p>In the <code>script.js</code> I have:</p>
<pre><code><script>
$(function(){
$("#mb_ticket_submit").submit(function(a){
a.preventDefault();
$.ajax({
method: "POST",
url: "validation.php",
data: {
mb_ticket_subject: $("#mb_ticket_subject").val(),
mb_ticket_content: $("#mb_ticket_content").val(),
mb_ticket_tax_stage: $("#mb_ticket_tax_stage option:selected").val(),
mb_ticket_tax_application: $("#mb_ticket_tax_application option:selected").val(),
mb_ticket_meta_date: $("#mb_ticket_meta_date").val(),
mb_ticket_meta_user_name: $("#mb_ticket_meta_user_name").val(),
mb_ticket_meta_user_email: $("#mb_ticket_meta_user_email").val(),
},
success: function(a){ $("div#response").show().html(a); },
});
})
});
</script>
</code></pre>
<p>Then finally the <code>validation.php</code> has the following (the $var are cleaned up, and validated from their <code>$_POST[]</code>:</p>
<pre><code> if( empty($form_ticket_meta_user_name) ) { die( 'Doesn\'t look like you have logged in properly'; ) }
if( empty($form_ticket_meta_user_email) ) { die( 'Doesn\'t look like you have logged in properly'; ) }
if( !empty($form_ticket_meta_user_email) ){ if( !filter_var($form_ticket_meta_user_email, FILTER_VALIDATE_EMAIL) ) { die( 'Doesn\'t look like your email address is formatted properly. Contact your administrator.' ); } }
if( empty($form_ticket_subject) ) { die( 'No subject' ); }
if( empty($form_ticket_content) ) { die( 'No content' ); }
if( empty($form_ticket_tax_stage) ) { die( 'No stage'); }
if( empty($form_ticket_tax_application) ) { die( 'No app' ); }
if( empty($form_ticket_tax_priority) ) { die( 'No priority' ); }
if( empty($form_ticket_tax_location) ) { die( 'No location' ); }
</code></pre>
<p>Thanks :)</p>
| [
{
"answer_id": 237958,
"author": "Manthan Dave",
"author_id": 83209,
"author_profile": "https://wordpress.stackexchange.com/users/83209",
"pm_score": -1,
"selected": false,
"text": "<p>Tried below object parametes</p>\n\n<pre><code>array(\n 'key' => 'post_code',\n ... | 2016/09/02 | [
"https://wordpress.stackexchange.com/questions/237986",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17411/"
] | I have three files: `submit.php` (a page), `validation.php`, `script.php`
I am trying to use the fields as a front end submission area via the `wp_insert_post()` function.
However, I don't know exactly where to put the function, as where I try either is before the `validation.php` file or if I put it in that file it causes an error since it can't pass wordpress functions.
I have tried playing with the `success` in the `$.ajax` but since the `die()` functions all result in it being successful can't trigger a create post.
Does anyone have a better solution?
In the `submit.php` I have a form:
```
<div class="" id="response"></div>
<form id="form_ticket_submit" method="post">
<label for="form_ticket_subject">Subject of issue</label>
<input id="form_ticket_subject" name="form_ticket_subject" type="text">
<label for="form_ticket_content">Post</label>
<textarea id="form_ticket_content" name="form_ticket_content"></textarea>
<label for="form_ticket_tax_stage">Select Stage</label>
<select id="form_ticket_tax_stage" name="form_ticket_tax_stage">
<option value="">Select one</option>
<?php foreach ($form_ticket_tax_cat_stage as $form_cat_stage) { echo '<option value="' . $form_cat_stage->slug . '">'. $form_cat_stage->name . '</option>'; } ?>
</select>
<input hidden="hidden" id="form_ticket_meta_date" name="form_ticket_meta_date" type="text" readonly="readonly" value="<?php echo get_date_from_gmt( date( 'Y-m-d H:i:s' ), 'jS \of F, Y H:i:s' ); ?>">
<input hidden="hidden" id="form_ticket_meta_user_name" name="form_ticket_meta_user_name" type="text" readonly="readonly" value="<?php echo $form_ticket_current_user_name; ?>">
<input hidden="hidden" id="form_ticket_meta_user_email" name="form_ticket_meta_user_email" type="text" readonly="readonly" value="<?php echo $form_ticket_current_user_email; ?>">
<input name="submit" type="submit" value="Submit Ticket" />
</form>
```
In the `script.js` I have:
```
<script>
$(function(){
$("#mb_ticket_submit").submit(function(a){
a.preventDefault();
$.ajax({
method: "POST",
url: "validation.php",
data: {
mb_ticket_subject: $("#mb_ticket_subject").val(),
mb_ticket_content: $("#mb_ticket_content").val(),
mb_ticket_tax_stage: $("#mb_ticket_tax_stage option:selected").val(),
mb_ticket_tax_application: $("#mb_ticket_tax_application option:selected").val(),
mb_ticket_meta_date: $("#mb_ticket_meta_date").val(),
mb_ticket_meta_user_name: $("#mb_ticket_meta_user_name").val(),
mb_ticket_meta_user_email: $("#mb_ticket_meta_user_email").val(),
},
success: function(a){ $("div#response").show().html(a); },
});
})
});
</script>
```
Then finally the `validation.php` has the following (the $var are cleaned up, and validated from their `$_POST[]`:
```
if( empty($form_ticket_meta_user_name) ) { die( 'Doesn\'t look like you have logged in properly'; ) }
if( empty($form_ticket_meta_user_email) ) { die( 'Doesn\'t look like you have logged in properly'; ) }
if( !empty($form_ticket_meta_user_email) ){ if( !filter_var($form_ticket_meta_user_email, FILTER_VALIDATE_EMAIL) ) { die( 'Doesn\'t look like your email address is formatted properly. Contact your administrator.' ); } }
if( empty($form_ticket_subject) ) { die( 'No subject' ); }
if( empty($form_ticket_content) ) { die( 'No content' ); }
if( empty($form_ticket_tax_stage) ) { die( 'No stage'); }
if( empty($form_ticket_tax_application) ) { die( 'No app' ); }
if( empty($form_ticket_tax_priority) ) { die( 'No priority' ); }
if( empty($form_ticket_tax_location) ) { die( 'No location' ); }
```
Thanks :) | **SOLUTION**
The Solution Accepted below worked, however, I wanted to know how is it working?
This is how it's working
```
SELECT * FROM wp_posts p, wp_postmeta m1, wp_postmeta m2
WHERE p.ID = m1.post_id and p.ID = m2.post_id
AND m1.meta_key = 'key1' AND m1.meta_value = 'value1'
AND m2.meta_key = 'key2' AND m2.meta_value = 'value2'
AND p.post_type = 'cpt' AND p.post_status = 'published'
``` |
238,005 | <p>I've been using an added function to load a modified rss template.
Works fine, but now I need to add a custom template for a CPT.</p>
<p>I have code for each,which works ok, but can't be used together because one over-rides the other.</p>
<p>I don't know enough php to modify.</p>
<p>Here's the code I'm using...</p>
<pre><code>remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', function() {
if ( $rss_template = locate_template( '/feeds/notes-feed.php' ) )
load_template( $rss_template );
else
do_feed_rss2(); // Call default function
}, 10, 1 );
</code></pre>
<p>and</p>
<pre><code>remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'item_feed_rss2', 10, 1 );
function item_feed_rss2() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
if( get_query_var( 'post_type' ) == 'item' and file_exists( $rss_template ) )
load_template( $rss_template );
else
do_feed_rss2(); // Call default function
</code></pre>
<p>Not knowing enough, I'm wondering if I can use this...</p>
<pre><code>remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'item_feed_rss2', 10, 1 );
function item_feed_rss2() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
$rss_template_notes = get_template_directory() . '/feeds/notes-feed.php';
if( get_query_var( 'post_type' ) == 'item' and file_exists( $rss_template ) )
load_template( $rss_template );
elseif( get_query_var( 'post' ) and file_exists( $rss_template_notes ) )
load_template( $rss_template_notes );
else
do_feed_rss2(); // Call default function
</code></pre>
| [
{
"answer_id": 238022,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>Just combine the logic for the two together. :)</p>\n\n<p>Use a single callback and depending on current context ov... | 2016/09/02 | [
"https://wordpress.stackexchange.com/questions/238005",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63350/"
] | I've been using an added function to load a modified rss template.
Works fine, but now I need to add a custom template for a CPT.
I have code for each,which works ok, but can't be used together because one over-rides the other.
I don't know enough php to modify.
Here's the code I'm using...
```
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', function() {
if ( $rss_template = locate_template( '/feeds/notes-feed.php' ) )
load_template( $rss_template );
else
do_feed_rss2(); // Call default function
}, 10, 1 );
```
and
```
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'item_feed_rss2', 10, 1 );
function item_feed_rss2() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
if( get_query_var( 'post_type' ) == 'item' and file_exists( $rss_template ) )
load_template( $rss_template );
else
do_feed_rss2(); // Call default function
```
Not knowing enough, I'm wondering if I can use this...
```
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', 'item_feed_rss2', 10, 1 );
function item_feed_rss2() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
$rss_template_notes = get_template_directory() . '/feeds/notes-feed.php';
if( get_query_var( 'post_type' ) == 'item' and file_exists( $rss_template ) )
load_template( $rss_template );
elseif( get_query_var( 'post' ) and file_exists( $rss_template_notes ) )
load_template( $rss_template_notes );
else
do_feed_rss2(); // Call default function
``` | Answering my own question, I’ll add this in case it’s of use to someone.
It seems to work ok with…
```
// This delivers valid feeds, with the correct templates.
remove_all_actions( 'do_feed_rss2' );
add_action( 'do_feed_rss2', function() {
$rss_template = get_template_directory() . '/feeds/item-feed.php';
$rss_template2 = get_template_directory() . '/feeds/notes-feed.php';
//if ( $post_type = 'item' )
if( get_query_var( 'post_type' ) == 'item' and file_exists($rss_template ) )
load_template($rss_template);
elseif ( $post_type = 'post' )
load_template($rss_template2);
else
do_feed_rss2(); // Call default function
}, 10, 1 );
```
This enables use of a custom template for the feed of normal posts, and use of a different custom template for the feed of the CPT ‘item’.
The feeds differ in channel title/link/description. |
238,006 | <p>just wondering if anyone came across this: I have a front page featuring artists in a square grid, now the client asks for a switch button to reorder the artist from A-Z (based on artist name) to the conventional newest post first - but this shall happen without reloading the page.</p>
<p>I found a solution with giving a parameter and then reload the page updating the query, but client wants this happing "on the fly" like here: <a href="http://selectiveartists.com/" rel="nofollow">http://selectiveartists.com/</a></p>
<p>Probably there is a solution to change order of posts with help of some JQuery (Plugin)?</p>
| [
{
"answer_id": 238009,
"author": "EBennett",
"author_id": 91050,
"author_profile": "https://wordpress.stackexchange.com/users/91050",
"pm_score": 1,
"selected": false,
"text": "<p>With WordPress you can utilise a function called <a href=\"https://codex.wordpress.org/Function_Reference/wp... | 2016/09/02 | [
"https://wordpress.stackexchange.com/questions/238006",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83211/"
] | just wondering if anyone came across this: I have a front page featuring artists in a square grid, now the client asks for a switch button to reorder the artist from A-Z (based on artist name) to the conventional newest post first - but this shall happen without reloading the page.
I found a solution with giving a parameter and then reload the page updating the query, but client wants this happing "on the fly" like here: <http://selectiveartists.com/>
Probably there is a solution to change order of posts with help of some JQuery (Plugin)? | With WordPress you can utilise a function called [wp\_localize\_script()](https://codex.wordpress.org/Function_Reference/wp_localize_script) which allows you to pass in a script, and a variable you would like that script to have access too.
Perhaps by assigning the new query to a variable, and then accessing it within jQuery would help you solve your problem.
The example provided by WordPress explains it pretty clearly:
```
<?php
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$translation_array = array(
'some_string' => __( 'Some string to translate', 'plugin-domain' ),
'a_value' => '10');
wp_localize_script( 'some_handle', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
?>
```
And then access like so:
```
<script>
// alerts 'Some string to translate'
alert( object_name.some_string);
</script>
```
So as you can see Javascript is now getting access to the variable translation\_array variable by getting hold of the object\_name which is tied to the variable $translation\_array and is then pulling the value of some\_string from the array.
So we could write something along the lines of:
```
<?php
$args = array('order' => 'ASC');
$get_artists = get_posts($args);
wp_register_script('artists', 'path/to/artists.js');
wp_localize_script('artists', 'artist_sort', $get_artists);
wp_enqueue_script('artists');
?>
```
And then access the variable within our artists.js script.
*[ No Idea if this works, as I haven't tested it, just purely an example in how you might be able to go about it ]* |
238,010 | <p>I've added additional tabs to my product pages within my functions.php file and now need to wrap that in an if statement so the additional tabs only show on products within the category of "Models." I've tried every way of doing it that I can find, and none of them work. They all get rid of the additional tabs on every page, even if it's in the category specified.</p>
<p>I've tried everything mentioned on <a href="https://wordpress.stackexchange.com/questions/75906/how-to-check-if-the-product-is-in-a-certain-category-on-a-single-product-php-in">this question</a>, and I'm assuming none of them have worked because that person is making edits to their single-product.php file, and I'm editing my functions.php file?</p>
<pre><code>if ( is_product() && has_term( 'Models', 'product_cat' ) ) {
////Add Custom Tabs
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
// Adds a compare tab
$tabs['compare'] = array(
'title' => __( 'Compare', 'woocommerce' ),
'id' => 'compare',
'priority' => 50,
'callback' => 'woo_compare_tab_content'
);
// Adds a warranty tab
$tabs['warranty'] = array(
'title' => __( 'Warranty', 'woocommerce' ),
'id' => 'warranty',
'priority' => 50,
'callback' => 'woo_warranty_tab_content'
);
return $tabs;
}
function woo_warranty_tab_content() {
$warranty = get_post_meta( get_the_ID(), 'wpcf-warranty', true );
// Warranty Tab Content
echo '<div class="fusion-title title sep-double">';
echo '<h3 class="title-heading-left">Warranty</h3>';
echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
echo '</div>';
echo "$warranty";
}
function woo_compare_tab_content() {
$compare = get_post_meta( get_the_ID(), 'wpcf-compare', true );
// Comparison Tab Content
echo '<div class="fusion-title title sep-double">';
echo '<h3 class="title-heading-left">Compare</h3>';
echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
echo '</div>';
echo "$compare";
}
}
</code></pre>
| [
{
"answer_id": 238009,
"author": "EBennett",
"author_id": 91050,
"author_profile": "https://wordpress.stackexchange.com/users/91050",
"pm_score": 1,
"selected": false,
"text": "<p>With WordPress you can utilise a function called <a href=\"https://codex.wordpress.org/Function_Reference/wp... | 2016/09/02 | [
"https://wordpress.stackexchange.com/questions/238010",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85805/"
] | I've added additional tabs to my product pages within my functions.php file and now need to wrap that in an if statement so the additional tabs only show on products within the category of "Models." I've tried every way of doing it that I can find, and none of them work. They all get rid of the additional tabs on every page, even if it's in the category specified.
I've tried everything mentioned on [this question](https://wordpress.stackexchange.com/questions/75906/how-to-check-if-the-product-is-in-a-certain-category-on-a-single-product-php-in), and I'm assuming none of them have worked because that person is making edits to their single-product.php file, and I'm editing my functions.php file?
```
if ( is_product() && has_term( 'Models', 'product_cat' ) ) {
////Add Custom Tabs
add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
// Adds a compare tab
$tabs['compare'] = array(
'title' => __( 'Compare', 'woocommerce' ),
'id' => 'compare',
'priority' => 50,
'callback' => 'woo_compare_tab_content'
);
// Adds a warranty tab
$tabs['warranty'] = array(
'title' => __( 'Warranty', 'woocommerce' ),
'id' => 'warranty',
'priority' => 50,
'callback' => 'woo_warranty_tab_content'
);
return $tabs;
}
function woo_warranty_tab_content() {
$warranty = get_post_meta( get_the_ID(), 'wpcf-warranty', true );
// Warranty Tab Content
echo '<div class="fusion-title title sep-double">';
echo '<h3 class="title-heading-left">Warranty</h3>';
echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
echo '</div>';
echo "$warranty";
}
function woo_compare_tab_content() {
$compare = get_post_meta( get_the_ID(), 'wpcf-compare', true );
// Comparison Tab Content
echo '<div class="fusion-title title sep-double">';
echo '<h3 class="title-heading-left">Compare</h3>';
echo '<div class="title-sep-container"><div class="title-sep sep-double"></div></div>';
echo '</div>';
echo "$compare";
}
}
``` | With WordPress you can utilise a function called [wp\_localize\_script()](https://codex.wordpress.org/Function_Reference/wp_localize_script) which allows you to pass in a script, and a variable you would like that script to have access too.
Perhaps by assigning the new query to a variable, and then accessing it within jQuery would help you solve your problem.
The example provided by WordPress explains it pretty clearly:
```
<?php
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$translation_array = array(
'some_string' => __( 'Some string to translate', 'plugin-domain' ),
'a_value' => '10');
wp_localize_script( 'some_handle', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
?>
```
And then access like so:
```
<script>
// alerts 'Some string to translate'
alert( object_name.some_string);
</script>
```
So as you can see Javascript is now getting access to the variable translation\_array variable by getting hold of the object\_name which is tied to the variable $translation\_array and is then pulling the value of some\_string from the array.
So we could write something along the lines of:
```
<?php
$args = array('order' => 'ASC');
$get_artists = get_posts($args);
wp_register_script('artists', 'path/to/artists.js');
wp_localize_script('artists', 'artist_sort', $get_artists);
wp_enqueue_script('artists');
?>
```
And then access the variable within our artists.js script.
*[ No Idea if this works, as I haven't tested it, just purely an example in how you might be able to go about it ]* |
238,011 | <p>I had been assuming that <code>ID</code> in <code>wp_posts</code> is the primary key and that <code>post_id</code> in <code>wp_postmeta</code> is the foreign key but there is no relationship between them.</p>
<p>How does these two tables relate each other? There is a <code>meta_key</code> and <code>meta_value</code> column where <code>meta_key</code> data are <code>_sku</code>, <code>_price</code>, and <code>_stock</code>. How can I use the <code>SELECT</code> or <code>UPDATE</code> query on <code>_sku</code>, <code>_price</code>, <code>_stock</code> if they are all in the same column?</p>
| [
{
"answer_id": 238020,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>post_id</code> column in the <code>wp_postmeta</code> table <em>is</em> a reference to the <code>... | 2016/09/02 | [
"https://wordpress.stackexchange.com/questions/238011",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102107/"
] | I had been assuming that `ID` in `wp_posts` is the primary key and that `post_id` in `wp_postmeta` is the foreign key but there is no relationship between them.
How does these two tables relate each other? There is a `meta_key` and `meta_value` column where `meta_key` data are `_sku`, `_price`, and `_stock`. How can I use the `SELECT` or `UPDATE` query on `_sku`, `_price`, `_stock` if they are all in the same column? | The `post_id` column in the `wp_postmeta` table *is* a reference to the `ID` column in the `wp_posts` table.
I'd suggest using the native [update\_post\_meta()](https://codex.wordpress.org/Function_Reference/update_post_meta) function in WordPress to update the meta data.
E.g. (Post ID is 123 in this example, and we're updating the price to 100.00):
```
update_post_meta(123, '_price', '100.00');
```
Here is the SQL equivalent:
```
UPDATE wp_postmeta
SET meta_value = 100.00
WHERE meta_key like '_price' AND post_id = 123;
``` |
238,038 | <p>I have recently add this function found in <a href="https://wordpress.stackexchange.com/questions/89767/how-to-increase-the-character-limit-for-post-name-of-200">this post</a> to increase my posts title limit of charcters from 200 to custom length, the problem now is that when I click publish, the posts are saved as drafts and I can't publish it cause I have only 2 choices </p>
<ul>
<li>Pending review</li>
<li>Draft</li>
</ul>
<p>Here is the function I have added to my functions file:</p>
<pre><code><?php
remove_filter( 'sanitize_title', 'sanitize_title_with_dashes' );
// add our custom hook
add_filter( 'sanitize_title', 'wpse8170_sanitize_title_with_dashes', 10, 3 );
function wpse8170_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 1000); // <--- here is the trick!
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
if ( 'save' == $context ) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Strip these characters entirely
$title = str_replace( array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// grave accent, acute accent, macron, caron
'%cc%80', '%cc%81', '%cc%84', '%cc%8c',
), '', $title );
// Convert times to x
$title = str_replace( '%c3%97', 'x', $title );
}
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
} ?>
</code></pre>
| [
{
"answer_id": 238042,
"author": "iyrin",
"author_id": 33393,
"author_profile": "https://wordpress.stackexchange.com/users/33393",
"pm_score": 1,
"selected": false,
"text": "<p>You simply need to copy the current function <code>sanitize_title_with_dashes</code> from <a href=\"https://cor... | 2016/09/02 | [
"https://wordpress.stackexchange.com/questions/238038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98757/"
] | I have recently add this function found in [this post](https://wordpress.stackexchange.com/questions/89767/how-to-increase-the-character-limit-for-post-name-of-200) to increase my posts title limit of charcters from 200 to custom length, the problem now is that when I click publish, the posts are saved as drafts and I can't publish it cause I have only 2 choices
* Pending review
* Draft
Here is the function I have added to my functions file:
```
<?php
remove_filter( 'sanitize_title', 'sanitize_title_with_dashes' );
// add our custom hook
add_filter( 'sanitize_title', 'wpse8170_sanitize_title_with_dashes', 10, 3 );
function wpse8170_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 1000); // <--- here is the trick!
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
if ( 'save' == $context ) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Strip these characters entirely
$title = str_replace( array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// grave accent, acute accent, macron, caron
'%cc%80', '%cc%81', '%cc%84', '%cc%8c',
), '', $title );
// Convert times to x
$title = str_replace( '%c3%97', 'x', $title );
}
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
} ?>
``` | You simply need to copy the current function `sanitize_title_with_dashes` from <https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/formatting.php#L1948> and change the following line:
```
$title = utf8_uri_encode($title, 200);
```
To this:
```
$title = utf8_uri_encode($title, 1000);
```
**Minor edit: Always refer to the source for the same version of WordPress you have installed. In most cases, it should be the current version.**
The script you are using does not match the current function from formatting.php ([compare differences here](https://www.diffchecker.com/3Jo4HfsD)). Particularly, the following two lines appear after the `if ( 'save' == $context )` condition is triggered in the original function:
```
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
```
---
Example
-------
Below is the same function as `sanitize_title_with_dashes` renamed as your new function `wpse8170_sanitize_title_with_dashes`. Only the value in `utf8_uri_encode()` has been changed:
```
function wpse8170_sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 1000);
}
$title = strtolower($title);
if ( 'save' == $context ) {
// Convert nbsp, ndash and mdash to hyphens
$title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
// Convert nbsp, ndash and mdash HTML entities to hyphens
$title = str_replace( array( ' ', ' ', '–', '–', '—', '—' ), '-', $title );
// Strip these characters entirely
$title = str_replace( array(
// iexcl and iquest
'%c2%a1', '%c2%bf',
// angle quotes
'%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
// curly quotes
'%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
'%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
// copy, reg, deg, hellip and trade
'%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
// acute accents
'%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
// grave accent, macron, caron
'%cc%80', '%cc%84', '%cc%8c',
), '', $title );
// Convert times to x
$title = str_replace( '%c3%97', 'x', $title );
}
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
``` |
238,039 | <p>I'm wondering how to change the admin theme based on a user's role. Currently I can change the admin theme using a plugin (ex: <a href="https://wordpress.org/plugins/blue-admin/" rel="nofollow">Blue Admin</a>) - but I'm not sure how to make those changes based on a role (subscriber etc).</p>
<p>Would also like to have specific menu items / etc shown only for certain roles.</p>
<p>I have no problem diving into <code>functions.php</code> or anything else that may be needed to accomplish this - just hoping to be pointed in the right direction first.</p>
| [
{
"answer_id": 238041,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 0,
"selected": false,
"text": "<p>The admin color scheme is stored in <code>user_meta</code> as <code>admin_color</code> (default is '<em... | 2016/09/02 | [
"https://wordpress.stackexchange.com/questions/238039",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/41269/"
] | I'm wondering how to change the admin theme based on a user's role. Currently I can change the admin theme using a plugin (ex: [Blue Admin](https://wordpress.org/plugins/blue-admin/)) - but I'm not sure how to make those changes based on a role (subscriber etc).
Would also like to have specific menu items / etc shown only for certain roles.
I have no problem diving into `functions.php` or anything else that may be needed to accomplish this - just hoping to be pointed in the right direction first. | You can ~~set~~ force a specific Admin Color Scheme pro user role through a function.
*Personally I would first take away the option to select the scheme from profile.php (Back-end Users/Your Profile)*
Below is just an example function which does set a specific color scheme for specific user roles.
*Please make first make a backup of the functions.php before adding this function.*
```
/**
* Set Admin Color Scheme by Role
* Codex: {@link https://codex.wordpress.org/Roles_and_Capabilities}
* {@link https://codex.wordpress.org/Function_Reference/wp_get_current_user}
* @version WordPress 4.6
*/
add_filter( 'get_user_option_admin_color', 'wpse_238039_set_admin_color' );
function wpse_238039_set_admin_color()
{
$current_user = wp_get_current_user();
// Check for the user role
if ( user_can( $current_user, 'subscriber' ) )
{
// Remove the Admin Color Scheme picker
remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );
// Set the Admin Color Scheme you want for this role
return 'light';
}
if ( user_can( $current_user, 'contributor' ) )
{
remove_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );
return 'coffee';
}
} // end function
```
It is of course possible to leave the Admin Color Scheme option on the user Profile Page by removing those lines from the function.
>
> Would also like to have specific menu items / etc shown only for
> certain roles.
>
>
>
It is possible to add/remove items within another function with the same kind of IF statement blocks. Just be aware of what you do/want in a specific function, and use the correct [hooks](https://developer.wordpress.org/reference/hooks/)
>
> **Note:** see the @link urls in the function above for references.
>
>
> |
238,057 | <pre><code>function dwwp_admin_enqueue_scripts_mlm() {
wp_enqueue_style( 'dwwp-admin-css', plugins_url( 'css/admin-users.css', __FILE__ ) );
wp_enqueue_script( 'admin-users', plugins_url( 'js/admin-users.js', __FILE__ ) );
wp_enqueue_script( 'jquery', 'http://code.jquery.com/jquery-1.10.2.js' );
wp_enqueue_script( 'jquery-ui', 'http://code.jquery.com/ui/1.10.4/jquery-ui.js' );
wp_enqueue_style( 'jquery-style', 'http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css' );}
add_action( 'admin_enqueue_scripts', 'dwwp_admin_enqueue_scripts_mlm' );
</code></pre>
| [
{
"answer_id": 238068,
"author": "theodorhanu",
"author_id": 36255,
"author_profile": "https://wordpress.stackexchange.com/users/36255",
"pm_score": 1,
"selected": true,
"text": "<p>No. As wordpress codex states, you should use jquery and other javascript files provided by them. As for c... | 2016/09/03 | [
"https://wordpress.stackexchange.com/questions/238057",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101387/"
] | ```
function dwwp_admin_enqueue_scripts_mlm() {
wp_enqueue_style( 'dwwp-admin-css', plugins_url( 'css/admin-users.css', __FILE__ ) );
wp_enqueue_script( 'admin-users', plugins_url( 'js/admin-users.js', __FILE__ ) );
wp_enqueue_script( 'jquery', 'http://code.jquery.com/jquery-1.10.2.js' );
wp_enqueue_script( 'jquery-ui', 'http://code.jquery.com/ui/1.10.4/jquery-ui.js' );
wp_enqueue_style( 'jquery-style', 'http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css' );}
add_action( 'admin_enqueue_scripts', 'dwwp_admin_enqueue_scripts_mlm' );
``` | No. As wordpress codex states, you should use jquery and other javascript files provided by them. As for css files I think you can use yours.
Please check [this link](https://developer.wordpress.org/reference/functions/wp_enqueue_script/)( scroll down) for a list of already defined javascript files.
Also, you have to use local files as much as possible, unless you have no other way. So for example, if you have a js library, you should download it and include it in your theme/plugin files and not enqueue it using CDN or any other external link. Wordpress team will refuse to publish your theme/plugin if you include external js files without a good reason.
LE: for jquery-ui you only have to use this
```
wp_enqueue_script( 'jquery-ui')
```
or add it as a dependency of your own script like this
```
wp_enqueue_script('my-script', 'url-to-scrip', array('jquery-ui'))
``` |
238,107 | <p>I am using WordPress Media Library in my plugin in the backend. How to change the upload path for it dynamically? Can it be done during the enqueue, or when creating it in JavaScript?</p>
<p>I am using <code>wp_enqueue_media()</code> in <code>admin_enqueue_scripts</code> action, and later creating the media frame in Javascript using <code>wp.media</code>.</p>
<p>I've managed to change the directory when uploading using <code>plupload_default_params</code> filter, but I don't know how to hook into the <code>query-attachments</code> action that queries the files into the library.</p>
<p><strong>Update:</strong> After hours of tinkering I gave up and I went with a different solution. I am adding a new setting on plugin's edit page and resetting it otherwise. This way I can access the option in ajax calls.</p>
<pre><code>function change_upload_dir( $args ) {
$user_id = get_current_user_id();
$form = false;
if( defined('DOING_AJAX') && DOING_AJAX ) {
$form = get_option( 'test_edit_' . $user_id );
}
if($form || isset($_GET['type']) || isset($_POST['subfolder'])) {
// change upload path
</code></pre>
<p>And in the plugin construct: </p>
<pre><code> if( !(defined('DOING_AJAX') && DOING_AJAX)
&& false === strpos($_SERVER['REQUEST_URI'], 'wp-content') ) {
$edit = get_option( 'test_edit_' . get_current_user_id() );
if ( $edit && $edit != '' ) {
update_option( 'test_edit_' . get_current_user_id(), '' );
}
}
</code></pre>
<p>This works fine, unless the user opens a new tab and the setting gets reset.
It's fine for now, but I'd really like to know if there is an easier way to do that.</p>
| [
{
"answer_id": 238979,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 1,
"selected": false,
"text": "<p>Might wanna look at</p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/wp_upl... | 2016/09/03 | [
"https://wordpress.stackexchange.com/questions/238107",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75841/"
] | I am using WordPress Media Library in my plugin in the backend. How to change the upload path for it dynamically? Can it be done during the enqueue, or when creating it in JavaScript?
I am using `wp_enqueue_media()` in `admin_enqueue_scripts` action, and later creating the media frame in Javascript using `wp.media`.
I've managed to change the directory when uploading using `plupload_default_params` filter, but I don't know how to hook into the `query-attachments` action that queries the files into the library.
**Update:** After hours of tinkering I gave up and I went with a different solution. I am adding a new setting on plugin's edit page and resetting it otherwise. This way I can access the option in ajax calls.
```
function change_upload_dir( $args ) {
$user_id = get_current_user_id();
$form = false;
if( defined('DOING_AJAX') && DOING_AJAX ) {
$form = get_option( 'test_edit_' . $user_id );
}
if($form || isset($_GET['type']) || isset($_POST['subfolder'])) {
// change upload path
```
And in the plugin construct:
```
if( !(defined('DOING_AJAX') && DOING_AJAX)
&& false === strpos($_SERVER['REQUEST_URI'], 'wp-content') ) {
$edit = get_option( 'test_edit_' . get_current_user_id() );
if ( $edit && $edit != '' ) {
update_option( 'test_edit_' . get_current_user_id(), '' );
}
}
```
This works fine, unless the user opens a new tab and the setting gets reset.
It's fine for now, but I'd really like to know if there is an easier way to do that. | Might wanna look at
<https://developer.wordpress.org/reference/functions/wp_upload_dir/>
In definition there is a hook `upload_dir`, you can use that to change `path`.
Haven't tried or tested it, but you can give it a try. |
238,129 | <p>I am trying to access post meta for custom post type and taxonomy using WP_Query and then query the posts with that specific post meta.
<br />
So far I have tied the following code:</p>
<pre><code>$hot_args = array(
'post_type' => 'video',
'posts_per_page' => '6',
"order" => "DESC",
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'date_query' => array(
array(
'after' => '1 week ago'
)
),
"post__not_in" => $posts__not_in,
'tax_query' => array(
array(
'taxonomy' => 'video_cat',
'field' => 'slug',
'terms' => "all"
)
),
);
$hot_query = new WP_Query( $hot_args );
</code></pre>
<p>This code doesn't work and not returning any results.<br /><br />
For normal posts this piece of code works but for custom post type doesn't, How can I make it work for custom post types?</p>
| [
{
"answer_id": 238115,
"author": "rayrutjes",
"author_id": 99248,
"author_profile": "https://wordpress.stackexchange.com/users/99248",
"pm_score": 2,
"selected": false,
"text": "<p>Moving a WordPress website is fairly easy, here are the steps:</p>\n\n<ul>\n<li>Backup your mysql database ... | 2016/09/04 | [
"https://wordpress.stackexchange.com/questions/238129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76334/"
] | I am trying to access post meta for custom post type and taxonomy using WP\_Query and then query the posts with that specific post meta.
So far I have tied the following code:
```
$hot_args = array(
'post_type' => 'video',
'posts_per_page' => '6',
"order" => "DESC",
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'date_query' => array(
array(
'after' => '1 week ago'
)
),
"post__not_in" => $posts__not_in,
'tax_query' => array(
array(
'taxonomy' => 'video_cat',
'field' => 'slug',
'terms' => "all"
)
),
);
$hot_query = new WP_Query( $hot_args );
```
This code doesn't work and not returning any results.
For normal posts this piece of code works but for custom post type doesn't, How can I make it work for custom post types? | Moving a WordPress website is fairly easy, here are the steps:
* Backup your mysql database and re-import it in the new environment,
* Move all the files to the new environment,
* Update the `wp-config.php` file to reflect the new database connection information,
* (\*)Replace all occurrences of your domain name with the new one if it has changed
(\*) This is the step that is confusing most of the time. People sometimes think it is enough to simply replace the few options in the database where the domain name appears but that is unfortunately not enough.
Indeed WordPress uses the PHP serialize/unserialize functions to store arrays in the the database. The problem here is that if you simply replace the domain name contained in a serialized object, you corrupt the data and will be unable to deserialize it because PHP serialization will add the length of every variable as part of the data. So unless you actually replace your domain name with another of the same size, you can not simply do a database search and replace.
**Fortunately there are 2 easy solutions:**
1. This script: <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/>
You simply deploy the folder in the root of your install and access it over http. **Do not forget to delete the folder once you are finished**
2. This CLI: <http://wp-cli.org/commands/search-replace/>
Solution that I personally prefer because it does far more than just search & replace and can help you keeping a healthy WordPress instance. |
238,141 | <p>I am Creating a Multi row , 2 Columns blog Post like this </p>
<pre><code>Post #1 | Post #4
Post #2 | Post #5
Post #3 | Post #6
</code></pre>
<p>I have found some post useful</p>
<p><a href="https://digwp.com/2010/03/wordpress-post-content-multiple-columns/" rel="nofollow noreferrer">https://digwp.com/2010/03/wordpress-post-content-multiple-columns/</a></p>
<p>Based on the post I have Created Code as follows</p>
<pre><code><?php
// Some sample styles for the images
echo "<style type='text/css'>
div#left-column {
width: 150px;
float: left;
clear: none;
}
div#right-column {
width: 150px;
float: left;
clear: none;
}
</style>\n";
?>
<div class="container">
<div class="row">
<div class="span6">
<div class="span4">
<?php if (have_posts()) :
while(have_posts()) :
$i++; ?>
<?php if(($i % 2) !== 0) :?>
<div id="left-column" class="col-xs-6">
<?php $wp_query->next_post();the_excerpt();?>
</div>
<div id="right-column" class="col-xs-6">
<?php else : the_post(); the_excerpt();?>
</div>
<?php endif; endwhile; else: ?>
<?php endif; ?>
<?php $i = 0; rewind_posts(); ?>
</div>
</div>
</code></pre>
<p>But this Code giving me Output like </p>
<p><a href="https://i.stack.imgur.com/Lm9lY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lm9lY.png" alt="enter image description here"></a></p>
<p>Either it is posting odd or even posts , and in distorted manner ...I Tried lot of things , But not able to get alternate post in horizontal direction , Either i am getting completely vertical or hoirizontal . Can anyone suggest what I am msssing , Any suggestion will be helpful</p>
| [
{
"answer_id": 238115,
"author": "rayrutjes",
"author_id": 99248,
"author_profile": "https://wordpress.stackexchange.com/users/99248",
"pm_score": 2,
"selected": false,
"text": "<p>Moving a WordPress website is fairly easy, here are the steps:</p>\n\n<ul>\n<li>Backup your mysql database ... | 2016/09/04 | [
"https://wordpress.stackexchange.com/questions/238141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102175/"
] | I am Creating a Multi row , 2 Columns blog Post like this
```
Post #1 | Post #4
Post #2 | Post #5
Post #3 | Post #6
```
I have found some post useful
<https://digwp.com/2010/03/wordpress-post-content-multiple-columns/>
Based on the post I have Created Code as follows
```
<?php
// Some sample styles for the images
echo "<style type='text/css'>
div#left-column {
width: 150px;
float: left;
clear: none;
}
div#right-column {
width: 150px;
float: left;
clear: none;
}
</style>\n";
?>
<div class="container">
<div class="row">
<div class="span6">
<div class="span4">
<?php if (have_posts()) :
while(have_posts()) :
$i++; ?>
<?php if(($i % 2) !== 0) :?>
<div id="left-column" class="col-xs-6">
<?php $wp_query->next_post();the_excerpt();?>
</div>
<div id="right-column" class="col-xs-6">
<?php else : the_post(); the_excerpt();?>
</div>
<?php endif; endwhile; else: ?>
<?php endif; ?>
<?php $i = 0; rewind_posts(); ?>
</div>
</div>
```
But this Code giving me Output like
[](https://i.stack.imgur.com/Lm9lY.png)
Either it is posting odd or even posts , and in distorted manner ...I Tried lot of things , But not able to get alternate post in horizontal direction , Either i am getting completely vertical or hoirizontal . Can anyone suggest what I am msssing , Any suggestion will be helpful | Moving a WordPress website is fairly easy, here are the steps:
* Backup your mysql database and re-import it in the new environment,
* Move all the files to the new environment,
* Update the `wp-config.php` file to reflect the new database connection information,
* (\*)Replace all occurrences of your domain name with the new one if it has changed
(\*) This is the step that is confusing most of the time. People sometimes think it is enough to simply replace the few options in the database where the domain name appears but that is unfortunately not enough.
Indeed WordPress uses the PHP serialize/unserialize functions to store arrays in the the database. The problem here is that if you simply replace the domain name contained in a serialized object, you corrupt the data and will be unable to deserialize it because PHP serialization will add the length of every variable as part of the data. So unless you actually replace your domain name with another of the same size, you can not simply do a database search and replace.
**Fortunately there are 2 easy solutions:**
1. This script: <https://interconnectit.com/products/search-and-replace-for-wordpress-databases/>
You simply deploy the folder in the root of your install and access it over http. **Do not forget to delete the folder once you are finished**
2. This CLI: <http://wp-cli.org/commands/search-replace/>
Solution that I personally prefer because it does far more than just search & replace and can help you keeping a healthy WordPress instance. |
238,146 | <p>I have 2 taxonomy sets <strong><code>product_cat</code></strong> and <strong><code>tvshows_cat</code></strong>.</p>
<p>There are 12 terms for each of them. A product may get 1 or 12 terms applied.</p>
<p>I use this code to show the term list in the product page:</p>
<pre>
$cats = get_the_term_list($post->ID, 'product_cat', '', ' ', '');
$tvcats = get_the_term_list($post->ID, 'tvshows_cat', '', ' ', '');
if (!empty($cats)){
echo strip_tags($cats, ' ');
}elseif(!empty($tvcats)){
echo strip_tags($tvcats, ' ');
}
</pre>
<p>The result is: </p>
<p><b><i>Action, Drama, Adventure, Biography, Animation</I></b></p>
<p>The problem is it doesn't have enough space to show all of the terms. </p>
<p>I need to limit number of terms to 2 terms.</p>
<p>Question</p>
<p>How can I limit the number of terms applied to two?</p>
| [
{
"answer_id": 238149,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 0,
"selected": false,
"text": "<p>We can limit the number of displayed terms with</p>\n\n<pre><code>// Add filter\nadd_filter( 'get_the_terms',... | 2016/09/04 | [
"https://wordpress.stackexchange.com/questions/238146",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101903/"
] | I have 2 taxonomy sets **`product_cat`** and **`tvshows_cat`**.
There are 12 terms for each of them. A product may get 1 or 12 terms applied.
I use this code to show the term list in the product page:
```
$cats = get_the_term_list($post->ID, 'product_cat', '', ' ', '');
$tvcats = get_the_term_list($post->ID, 'tvshows_cat', '', ' ', '');
if (!empty($cats)){
echo strip_tags($cats, ' ');
}elseif(!empty($tvcats)){
echo strip_tags($tvcats, ' ');
}
```
The result is:
***Action, Drama, Adventure, Biography, Animation***
The problem is it doesn't have enough space to show all of the terms.
I need to limit number of terms to 2 terms.
Question
How can I limit the number of terms applied to two? | >
> **Instead using `get_the_term_list()` function, you should use `get_the_terms()` which will give you directly an array of terms** *(as `get_the_term_list()` is using `get_the_terms()` herself if you look to the source code of the function)*.
>
>
>
Then that you can build a **custom function** to get what you want *(I will **not use implode() function** or **any other one** php function as we want only 2 terms.)*
**Note:** You don't need `strip_tags()` function here
So your code will be:
```
// This function goes first
function get_my_terms( $post_id, $taxonomy ){
$cats = get_the_terms( $post_id, $taxonomy );
foreach($cats as $cat) $cats_arr[] = $cat->name;
if ( count($cats_arr) > 1) $cats_str = $cats_arr[0] . ', ' . $cats_arr[1]; // return first 2 terms
elseif ( count($cats_arr) == 1) $cats_str = $cats_arr[0]; // return one term
else $cats_str = '';
return $cats_str;
}
```
*This code goes in function.php file of your active child theme (or theme) or any plugin files…*
Then below is your code:
```
$cats = get_my_terms( $post->ID, 'product_cat' );
$tvcats = get_my_terms( $post->ID, 'tvshows_cat' );
// Displaying 2 categories terms max
echo $cats . $tvcats;
```
*This code goes on your php templates file*
>
> **— update —** Or without function, your code will be:
>
>
>
```
// Product categories
$cats = get_the_terms( $post->ID, 'product_cat' );
foreach($cats as $cat) $cats_arr[] = $cat->name;
if ( count($cats_arr) > 1) $cats_str = $cats_arr[0] . ', ' . $cats_arr[1]; // return first 2 terms
elseif ( count($cats_arr) == 1) $cats_str = $cats_arr[0]; // return one term
else $cats_str = '';
// TV shows categories
$tvcats = get_the_terms( $post->ID, 'tvshows_cat' );
foreach($tvcats as $tvcat) $tvcat_arr[] = $tvcat->name;
if ( count($tvcat_arr) > 1) $tvcats_str = $tvcat_arr[0] . ', ' . $tvcat_arr[1]; // return first 2 terms
elseif ( count($tvcat_arr) == 1) $tvcats_str = $tvcat_arr[0]; // return one term
else $tvcats_str = '';
// The Display of 2 categories
echo $cats_str . $tvcats_str;
```
This code goes on your **php templates** files |
238,170 | <p>So i'm working on a plugin where I assign a default avatar to anyone that comments. The line i'm stuck on contains a theme directory reference but I want to reference the image in the plugin directory instead. Thanks in advance!</p>
<pre><code>$new_avatar_url = get_bloginfo( 'plugin_directory' ) . '/avatar-1.jpg';
</code></pre>
| [
{
"answer_id": 238172,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Try <a href=\"https://codex.wordpress.org/Function_Reference/plugin_dir_url\" rel=\"nofollow\"><code>plugin_... | 2016/09/04 | [
"https://wordpress.stackexchange.com/questions/238170",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102192/"
] | So i'm working on a plugin where I assign a default avatar to anyone that comments. The line i'm stuck on contains a theme directory reference but I want to reference the image in the plugin directory instead. Thanks in advance!
```
$new_avatar_url = get_bloginfo( 'plugin_directory' ) . '/avatar-1.jpg';
``` | Try [`plugin_dir_url()`](https://codex.wordpress.org/Function_Reference/plugin_dir_url):
```
$new_avatar_url = plugin_dir_url( __FILE__ ) . '/avatar-1.jpg';
``` |
238,191 | <p>We have a section on the homepage where we'd like to show a different (random) post every 3 days.</p>
<p>I'm trying to figure out a way to do it. This would give us a weekly post, but I don't know how to get a post every 3 days...:</p>
<pre><code><?php
global $post;
$args = array(
'post_type' => 'girls_tips',
'posts_per_page' => 1,
'no_found_rows' => true,
'offset' => (date( 'W' ) - 1)
);
$posts = get_posts($args);
foreach($posts as $post):
setup_postdata($post);
?>
<h2><?php the_title(); ?></h2>
<?php endforeach; ?>
</code></pre>
<p>Any help would be appreciated!
Cheers,</p>
| [
{
"answer_id": 238188,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 3,
"selected": true,
"text": "<p>No script of function necessary. It's actually built into WordPress. Simply go to your page to edit a... | 2016/09/04 | [
"https://wordpress.stackexchange.com/questions/238191",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23411/"
] | We have a section on the homepage where we'd like to show a different (random) post every 3 days.
I'm trying to figure out a way to do it. This would give us a weekly post, but I don't know how to get a post every 3 days...:
```
<?php
global $post;
$args = array(
'post_type' => 'girls_tips',
'posts_per_page' => 1,
'no_found_rows' => true,
'offset' => (date( 'W' ) - 1)
);
$posts = get_posts($args);
foreach($posts as $post):
setup_postdata($post);
?>
<h2><?php the_title(); ?></h2>
<?php endforeach; ?>
```
Any help would be appreciated!
Cheers, | No script of function necessary. It's actually built into WordPress. Simply go to your page to edit and on the right hand side you should see a widget labeled *Publish*.
On the third line down, you will see an *Edit* button and you can set the date and time on when you want the page to be shown:
 |
238,210 | <p>I'm trying to display a list of categories in a PHP enabled text widget. On child category pages I need to get the id of the current category's parent category and then use that to return a list of all that category's child categories except the current category.</p>
<p>I tried the following code but it's not working:</p>
<pre><code><?php if (is_category( )) {
$thiscat = get_category( get_query_var( 'cat' ) );
$catid = $thiscat->cat_ID;
$parent = $catid->category_parent;
$catlist = get_categories(
array(
'child_of' => $parent,
'orderby' => 'id',
'order' => 'DESC',
'exclude' => $catid,
'hide_empty' => '0'
) );
} ?>
</code></pre>
<p>This displays both the parent categories and child categories.</p>
| [
{
"answer_id": 238215,
"author": "jrcollins",
"author_id": 68414,
"author_profile": "https://wordpress.stackexchange.com/users/68414",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to be working:</p>\n\n<pre><code><?php if (is_category( )) {\n\n$thiscat = get_category( get_... | 2016/09/05 | [
"https://wordpress.stackexchange.com/questions/238210",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
] | I'm trying to display a list of categories in a PHP enabled text widget. On child category pages I need to get the id of the current category's parent category and then use that to return a list of all that category's child categories except the current category.
I tried the following code but it's not working:
```
<?php if (is_category( )) {
$thiscat = get_category( get_query_var( 'cat' ) );
$catid = $thiscat->cat_ID;
$parent = $catid->category_parent;
$catlist = get_categories(
array(
'child_of' => $parent,
'orderby' => 'id',
'order' => 'DESC',
'exclude' => $catid,
'hide_empty' => '0'
) );
} ?>
```
This displays both the parent categories and child categories. | I now realize there's an easier way to do this:
```
<?php if (is_category( )) {
$thiscat = get_category( get_query_var( 'cat' ) );
$catid = $thiscat->cat_ID;
$parent = $thiscat->category_parent;
if (!empty ($parent) ) {
//child category pages
$catlist = get_categories(
array(
'child_of' => $parent,
'orderby' => 'id',
'order' => 'DESC',
'exclude' => $catid,
'hide_empty' => '0'
) );
}
} ?>
``` |
238,235 | <p>I'm trying to change the stylesheet for specific page/post while viewing in frontend, but I can't find the hook or filter for doing that ..</p>
<p>I've tried many hooks and pages and it doesn't work</p>
<p>Should I use <code>page_css_class</code> ?</p>
<pre><code>apply_filters( 'page_css_class', array $css_class, WP_Post $page, int $depth, array $args, int $current_page )
</code></pre>
| [
{
"answer_id": 238236,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": 0,
"selected": false,
"text": "<p>Look around for \"child theme\" of the theme you are using. Create something new. The basics for child ... | 2016/09/05 | [
"https://wordpress.stackexchange.com/questions/238235",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102188/"
] | I'm trying to change the stylesheet for specific page/post while viewing in frontend, but I can't find the hook or filter for doing that ..
I've tried many hooks and pages and it doesn't work
Should I use `page_css_class` ?
```
apply_filters( 'page_css_class', array $css_class, WP_Post $page, int $depth, array $args, int $current_page )
``` | The filter [`page_css_class`](https://developer.wordpress.org/reference/hooks/page_css_class/) allows you to change the classes on all pages, when they are listed. This is not what you are looking for.
In stead, you'll want to enqueue different style sheets for different posts/pages. This you can do using conditionals. Include a function like this in your `functions.php` (example will load a special style for the page with slug "about-us"):
```
function wpse238235_conditional_load_style() {
if (is_page('about-us')) {
wp_register_style('wpse238235-about-us-style', get_template_directory_uri() . '/about-us-style.css');
wp_enqueue_style('wpse238235-about-us-style');
}
else {
wp_register_style('wpse238235-default-style', get_template_directory_uri() . '/default-style.css');
wp_enqueue_style('wpse238235-default-style');
}
```
Beware that this assumes the mandatory `style.css` is also loaded somewhere. |
238,271 | <p>I have a custom post type of people with some custom taxonomy boxes, i want to hide these when on child pages. I have found remove_meta_box works fine but i just can't access the $post object within the action.</p>
<p>Currently i have</p>
<pre><code>function remove_post_custom_fields($post) {
global $post;
if( count($post->ancestors) > 0 ){
remove_meta_box( 'staff-typediv' , 'people' , 'normal' );
remove_meta_box( 'practice-areadiv' , 'people' , 'normal' );
}
}
add_action( 'admin_menu' , 'remove_post_custom_fields' );
</code></pre>
<p>I have tried <code>count($post->ancestors) > 0</code> and also just <code>$post->post_parent</code> but neither work.</p>
<p>Anyone any clue how to access $post variables within this action?</p>
| [
{
"answer_id": 238255,
"author": "montrealist",
"author_id": 8105,
"author_profile": "https://wordpress.stackexchange.com/users/8105",
"pm_score": 3,
"selected": true,
"text": "<p>Newer hosting providers that cater specifically to WordPress usually have tools in place to ease this pain. ... | 2016/09/05 | [
"https://wordpress.stackexchange.com/questions/238271",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/6123/"
] | I have a custom post type of people with some custom taxonomy boxes, i want to hide these when on child pages. I have found remove\_meta\_box works fine but i just can't access the $post object within the action.
Currently i have
```
function remove_post_custom_fields($post) {
global $post;
if( count($post->ancestors) > 0 ){
remove_meta_box( 'staff-typediv' , 'people' , 'normal' );
remove_meta_box( 'practice-areadiv' , 'people' , 'normal' );
}
}
add_action( 'admin_menu' , 'remove_post_custom_fields' );
```
I have tried `count($post->ancestors) > 0` and also just `$post->post_parent` but neither work.
Anyone any clue how to access $post variables within this action? | Newer hosting providers that cater specifically to WordPress usually have tools in place to ease this pain. I put my clients on Pantheon which has this [neat Git-enabled workflow](https://pantheon.io/docs/pantheon-workflow/), where code only moves up (from dev to staging to production) and DB stuff only moves down (vice versa from the code). Copying a database from production to staging is one click with their interface. Provided this workflow is respected, this pretty much eliminates the issue of ever messing up the production database, enabling me to always test my changes on a fresh clone of production DB data in either staging on development.
One doesn't have to use Pantheon - you can adopt a similar approach in your process using your own tools (Git + a DB cloning plugin like WP Migrate DB). I just find this way works well for me.
Question: why would you put your production site in maintenance mode while testing staging? There shouldn't be a need for that in a majority of cases. The only case I can think of is having some sort of very brittle system highly sensitive to additional user data being fed into it, with a catastrophic bug to boot - but that would likely be indicative of a different, larger, problem where one would need to rethink their product's entire architecture. |
238,293 | <p>Similar to generating an array of the admin menu/submenu:</p>
<pre><code>global $menu;
foreach ( $menu as $group => $item ) {
echo '<pre>'; print_r( $item ); echo '</pre>';
}
</code></pre>
<p>How can I get an array of all of the available menu items in the toolbar? I tried using the <code>global $wp_admin_bar</code> variable, but that seems to not be the right one.</p>
<p><img src="https://i.stack.imgur.com/R1KMD.png" alt="Toolbar" /></p>
<p>The reason why I want to generate this array is to use this in a plugin of mine to provide an option to choose which items to hide from the toolbar, allowing users to customize their settings. Right now, I manually created an array called <code>$toolbar</code> to choose the items I want to hide myself:</p>
<pre><code>global $wp_admin_bar;
$toolbar = array(
'wp-logo', // WordPress logo
'comments', // Comments
'new-post', // New > Post
'search' // Search
);
foreach ( $toolbar as $item ) {
$wp_admin_bar -> remove_menu( $item );
}
</code></pre>
<hr />
<h3>Update [2016-09-16]</h3>
<p>I was able to get the entire list by using the following in my plugin settings page:</p>
<pre><code>global $wp_admin_bar;
echo '<pre>'; print_r( $wp_admin_bar ); echo '</pre>';
</code></pre>
<p>It's too long to paste in here, so you can view the entire list on this <a href="http://pastebin.com/QfSaE5Tk" rel="nofollow noreferrer">Pastebin link</a>. However, below is a snippet of how it starts. How can I get all of the values that are in <code>[id] =></code> and/or <code>[parent] =></code>? It looks like I would need to go through a few levels of <code>foreach</code>?</p>
<pre><code>WP_Admin_Bar Object (
[nodes:WP_Admin_Bar:private] => Array (
[user-actions] => stdClass Object (
[id] => user-actions
[title] =>
[parent] => my-account
[href] =>
[meta] => Array (
[class] => ab-submenu
)
[children] => Array (
[0] => stdClass Object (
[id] => user-info
[title] => Name
[parent] => user-actions
[href] => http://example.com/wp-admin/profile.php
[meta] => Array (
[tabindex] => -1
)
[children] => Array (
)
[type] => item
)
[1] => stdClass Object (
[id] => edit-profile
[title] => Edit My Profile
[parent] => user-actions
[href] => http://example.com/wp-admin/profile.php
[meta] => Array (
)
[children] => Array (
)
[type] => item
)
and so on...
</code></pre>
| [
{
"answer_id": 238295,
"author": "Syed Fakhar Abbas",
"author_id": 90591,
"author_profile": "https://wordpress.stackexchange.com/users/90591",
"pm_score": 2,
"selected": false,
"text": "<p>There is an action hook <a href=\"https://developer.wordpress.org/?s=admin_bar_menu\" rel=\"nofollo... | 2016/09/05 | [
"https://wordpress.stackexchange.com/questions/238293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] | Similar to generating an array of the admin menu/submenu:
```
global $menu;
foreach ( $menu as $group => $item ) {
echo '<pre>'; print_r( $item ); echo '</pre>';
}
```
How can I get an array of all of the available menu items in the toolbar? I tried using the `global $wp_admin_bar` variable, but that seems to not be the right one.

The reason why I want to generate this array is to use this in a plugin of mine to provide an option to choose which items to hide from the toolbar, allowing users to customize their settings. Right now, I manually created an array called `$toolbar` to choose the items I want to hide myself:
```
global $wp_admin_bar;
$toolbar = array(
'wp-logo', // WordPress logo
'comments', // Comments
'new-post', // New > Post
'search' // Search
);
foreach ( $toolbar as $item ) {
$wp_admin_bar -> remove_menu( $item );
}
```
---
### Update [2016-09-16]
I was able to get the entire list by using the following in my plugin settings page:
```
global $wp_admin_bar;
echo '<pre>'; print_r( $wp_admin_bar ); echo '</pre>';
```
It's too long to paste in here, so you can view the entire list on this [Pastebin link](http://pastebin.com/QfSaE5Tk). However, below is a snippet of how it starts. How can I get all of the values that are in `[id] =>` and/or `[parent] =>`? It looks like I would need to go through a few levels of `foreach`?
```
WP_Admin_Bar Object (
[nodes:WP_Admin_Bar:private] => Array (
[user-actions] => stdClass Object (
[id] => user-actions
[title] =>
[parent] => my-account
[href] =>
[meta] => Array (
[class] => ab-submenu
)
[children] => Array (
[0] => stdClass Object (
[id] => user-info
[title] => Name
[parent] => user-actions
[href] => http://example.com/wp-admin/profile.php
[meta] => Array (
[tabindex] => -1
)
[children] => Array (
)
[type] => item
)
[1] => stdClass Object (
[id] => edit-profile
[title] => Edit My Profile
[parent] => user-actions
[href] => http://example.com/wp-admin/profile.php
[meta] => Array (
)
[children] => Array (
)
[type] => item
)
and so on...
``` | There is an action hook [admin\_bar\_menu](https://developer.wordpress.org/?s=admin_bar_menu) which will provide you an array of admin bar menu items.
```
add_action('admin_bar_menu', 'get_admin_bar_header_array');
public function get_admin_bar_header_array($admin_bar){
print_r($admin_bar);
}
```
:) |
238,314 | <p>I want to include a json manifest file in wordpress plugin but don't know how,
this is the file that i want to include in my plugin with <code>rel=manifest</code> and <code>href=manifest.json</code></p>
<p><code><link rel="manifest" href="/manifest.json"></code></p>
<p>How to do this in plugin ?</p>
| [
{
"answer_id": 238319,
"author": "user3114253",
"author_id": 76325,
"author_profile": "https://wordpress.stackexchange.com/users/76325",
"pm_score": 2,
"selected": false,
"text": "<p>Include this in you plugin</p>\n\n<pre><code>add_action( 'wp_head', 'inc_manifest_link' );\n\n// Creates ... | 2016/09/06 | [
"https://wordpress.stackexchange.com/questions/238314",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102268/"
] | I want to include a json manifest file in wordpress plugin but don't know how,
this is the file that i want to include in my plugin with `rel=manifest` and `href=manifest.json`
`<link rel="manifest" href="/manifest.json">`
How to do this in plugin ? | Include this in you plugin
```
add_action( 'wp_head', 'inc_manifest_link' );
// Creates the link tag
function inc_manifest_link() {
echo '<link rel="manifest" href="/manifest.json">';
}
```
what we are doing here is adding a hook to wp\_head action. |
238,330 | <p>I tried the example in this link <a href="https://codex.wordpress.org/Function_Reference/wp_embed_register_handler" rel="nofollow">https://codex.wordpress.org/Function_Reference/wp_embed_register_handler</a> but it didn't work. This is my whole code:</p>
<pre><code>add_action('init', function() {
wp_embed_register_handler( 'forbes', '#http://(?:www|video)\.forbes\.com/(?:video/embed/embed\.html|embedvideo/)\?show=([\d]+)&format=frame&height=([\d]+)&width=([\d]+)&video=(.+?)($|&)#i', 'wp_embed_handler_forbes' );
});
function wp_embed_handler_forbes( $matches, $attr, $url, $rawattr ) {
$embed = sprintf(
'<iframe src="http://www.forbes.com/video/embed/embed.html?show=%1$s&format=frame&height=%2$s&width=%3$s&video=%4$s&mode=render" width="%3$spx" height="%2$spx" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>',
esc_attr($matches[1]),
esc_attr($matches[2]),
esc_attr($matches[3]),
esc_attr($matches[4])
);
return apply_filters( 'embed_forbes', $embed, $matches, $attr, $url, $rawattr );
}
</code></pre>
<p>Any ideas why this is not working?</p>
| [
{
"answer_id": 238351,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I modified the example you posted from the Codex:</p>\n\n<pre><code>/**\n * Embed support for Forbes videos\n ... | 2016/09/06 | [
"https://wordpress.stackexchange.com/questions/238330",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102275/"
] | I tried the example in this link <https://codex.wordpress.org/Function_Reference/wp_embed_register_handler> but it didn't work. This is my whole code:
```
add_action('init', function() {
wp_embed_register_handler( 'forbes', '#http://(?:www|video)\.forbes\.com/(?:video/embed/embed\.html|embedvideo/)\?show=([\d]+)&format=frame&height=([\d]+)&width=([\d]+)&video=(.+?)($|&)#i', 'wp_embed_handler_forbes' );
});
function wp_embed_handler_forbes( $matches, $attr, $url, $rawattr ) {
$embed = sprintf(
'<iframe src="http://www.forbes.com/video/embed/embed.html?show=%1$s&format=frame&height=%2$s&width=%3$s&video=%4$s&mode=render" width="%3$spx" height="%2$spx" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>',
esc_attr($matches[1]),
esc_attr($matches[2]),
esc_attr($matches[3]),
esc_attr($matches[4])
);
return apply_filters( 'embed_forbes', $embed, $matches, $attr, $url, $rawattr );
}
```
Any ideas why this is not working? | I modified the example you posted from the Codex:
```
/**
* Embed support for Forbes videos
*
* Usage Example:
*
* http://www.forbes.com/video/5049647995001/
*/
add_action( 'init', function()
{
wp_embed_register_handler(
'forbes',
'#http://www\.forbes\.com/video/([\d]+)/?#i',
'wp_embed_handler_forbes'
);
} );
function wp_embed_handler_forbes( $matches, $attr, $url, $rawattr )
{
$embed = sprintf(
'<iframe class="forbes-video" src="https://players.brightcove.net/2097119709001/598f142b-5fda-4057-8ece-b03c43222b3f_default/index.html?videoId=%1$s" width="600" height="400" frameborder="0" scrolling="no"></iframe>',
esc_attr( $matches[1] )
);
return apply_filters( 'embed_forbes', $embed, $matches, $attr, $url, $rawattr );
}
```
Currently the `iframe` has a fixed *height* and *width*.
You can hopefully adjust it to your needs, e.g. using the theme's `$content_width` or pass on the height/width information directly from the pasted video url.
**Update:** I added a [warning to the Codex page](https://codex.wordpress.org/Function_Reference/wp_embed_register_handler#Examples), until a better example is posted. |
238,347 | <p>I have many duplicated post and I wanted remove them but Google already indexed them. So the idea is redirect all post with pattern [-number] in the end of the url to the same URL without number</p>
<p><code>www.domain.com/category/post-title[-number]</code> to <code>www.domain.com/category/post-title</code></p>
<p>Example:</p>
<pre><code>www.domain.com/category/post-title/
www.domain.com/category/post-title-1/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-2/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-3/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-4/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-5/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-6/ --> www.domain.com/category/post-title/
</code></pre>
<p>I have tried some Rewrite Rules on the .htaccess but didn't work at all.</p>
<p>For example this one:</p>
<pre><code>#RewriteRule ^/(.+)-[0-9]+/$ /$1 R=301
</code></pre>
<p><code>(.+)</code> --> it will match the letters of the 'post-title'</p>
<p><code>-[0-9]+/</code> --> It will match the '-' and the number of the tittle</p>
<p>Thanks!</p>
| [
{
"answer_id": 238354,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>you can test this in the 404 template and do a redirection </p>\n\n<p>try this : </p>\n\n<pre><code>add_filter(\"... | 2016/09/06 | [
"https://wordpress.stackexchange.com/questions/238347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65640/"
] | I have many duplicated post and I wanted remove them but Google already indexed them. So the idea is redirect all post with pattern [-number] in the end of the url to the same URL without number
`www.domain.com/category/post-title[-number]` to `www.domain.com/category/post-title`
Example:
```
www.domain.com/category/post-title/
www.domain.com/category/post-title-1/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-2/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-3/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-4/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-5/ --> www.domain.com/category/post-title/
www.domain.com/category/post-title-6/ --> www.domain.com/category/post-title/
```
I have tried some Rewrite Rules on the .htaccess but didn't work at all.
For example this one:
```
#RewriteRule ^/(.+)-[0-9]+/$ /$1 R=301
```
`(.+)` --> it will match the letters of the 'post-title'
`-[0-9]+/` --> It will match the '-' and the number of the tittle
Thanks! | You're close. Add the following to your `.htaccess` file in between the `<IfModule mod_rewrite.c>` tags that were created by WordPress:
```
RewriteCond %{HTTP_HOST}
RewriteRule ^(.+)-[0-9]+/$ /$1 [R=301]
```
Your `.htaccess` should looks like the following if it hasn't been modified by another plugin:
```
# 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]
# Custom Rewrite
RewriteCond %{HTTP_HOST}
RewriteRule ^(.+)-[0-9]+/$ /$1 [R=301]
</IfModule>
# END WordPress
```
As a result it will do the following:
```
http://example.com/category/post-title[-NUMBER]
```
Redirects to:
```
http://example.com/category/post-title
``` |
238,359 | <p>I tried to figure out how to separate the custom post type taxonomies.</p>
<pre><code>$terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, array( 'commitments', 'type' ) );
if( is_wp_error( $term_link ) )
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
}
</code></pre>
<p>Each taxonomies show correctly. However, I cannot separate them in comma. it shows "TaxonomyATaxonomyB" but I want to show it as "TaxonomyA, TaxonomyB"</p>
<p>How to do it? or is there any other way around?</p>
<p>Thanks!</p>
| [
{
"answer_id": 238362,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 4,
"selected": true,
"text": "<p>You can use a counter to determine if you need to add a comma or not :</p>\n\n<pre><code>$terms = get_the_t... | 2016/09/06 | [
"https://wordpress.stackexchange.com/questions/238359",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35253/"
] | I tried to figure out how to separate the custom post type taxonomies.
```
$terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) );
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, array( 'commitments', 'type' ) );
if( is_wp_error( $term_link ) )
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
}
```
Each taxonomies show correctly. However, I cannot separate them in comma. it shows "TaxonomyATaxonomyB" but I want to show it as "TaxonomyA, TaxonomyB"
How to do it? or is there any other way around?
Thanks! | You can use a counter to determine if you need to add a comma or not :
```
$terms = get_the_terms( $post->ID , array( 'commitments', 'type' ) );
// init counter
$i = 1;
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, array( 'commitments', 'type' ) );
if( is_wp_error( $term_link ) )
continue;
echo '<a href="' . $term_link . '">' . $term->name . '</a>';
// Add comma (except after the last theme)
echo ($i < count($terms))? ", " : "";
// Increment counter
$i++;
}
``` |
238,383 | <p>My feed uses the excerpt, and I want to remove a line of code containing an image.</p>
<p>Example format is...</p>
<pre><code><img class="pagehead" src="/graphics/magazine/307/1.jpg" alt="" />
</code></pre>
| [
{
"answer_id": 238384,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 1,
"selected": false,
"text": "<p>You can <a href=\"https://codex.wordpress.org/Customizing_Feeds\" rel=\"nofollow\">customize your feed lik... | 2016/09/06 | [
"https://wordpress.stackexchange.com/questions/238383",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63350/"
] | My feed uses the excerpt, and I want to remove a line of code containing an image.
Example format is...
```
<img class="pagehead" src="/graphics/magazine/307/1.jpg" alt="" />
``` | UPDATE...
Answering my own question, I'll add this in the hope it'll be useful to someone...
Whilst waiting for answers, I found a solution which seems to work fine.
```
function remove_images( $the_excerpt_rss ) {
$postOutput = preg_replace('/<img[^>]+./','', $the_excerpt_rss);
return $postOutput;}
add_filter( 'the_excerpt_rss', 'remove_images', 100 );
``` |
238,386 | <p>I downgraded to MAMP after trying MAMP pro, everything is fine except some of the links don’t have localhost port; eg…localhost/about, when it should be localhost:8888/about. Some of the links include the port, and some don’t, but I’m not sure why? Any ideas would be greatly appreciated. Thanks!</p>
| [
{
"answer_id": 238384,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 1,
"selected": false,
"text": "<p>You can <a href=\"https://codex.wordpress.org/Customizing_Feeds\" rel=\"nofollow\">customize your feed lik... | 2016/09/06 | [
"https://wordpress.stackexchange.com/questions/238386",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102305/"
] | I downgraded to MAMP after trying MAMP pro, everything is fine except some of the links don’t have localhost port; eg…localhost/about, when it should be localhost:8888/about. Some of the links include the port, and some don’t, but I’m not sure why? Any ideas would be greatly appreciated. Thanks! | UPDATE...
Answering my own question, I'll add this in the hope it'll be useful to someone...
Whilst waiting for answers, I found a solution which seems to work fine.
```
function remove_images( $the_excerpt_rss ) {
$postOutput = preg_replace('/<img[^>]+./','', $the_excerpt_rss);
return $postOutput;}
add_filter( 'the_excerpt_rss', 'remove_images', 100 );
``` |
238,395 | <p>I'm converting an existing website to a WordPress theme. One of the pages is a gallery that uses JS <code>history.pushState</code> to create unique URLs for loading certain images. </p>
<p>E.g. page URL (non WP website): <code>http://www.good-deeds-day.org/gallery/</code></p>
<p>URL for a certain image: <code>http://www.good-deeds-day.org/gallery/img-35</code></p>
<p>I would like to preserve this functionality in WordPress. However, when loading the URL for a certain image, WordPress considers it as a different page and displays a 404 error.</p>
<p>Is there a way to configure WordPress or <code>.htaccess</code> so that when such image URLs are loaded it will keep the URL and load the gallery page, thus displaying the relevant image in the gallery page?</p>
| [
{
"answer_id": 238399,
"author": "Rarst",
"author_id": 847,
"author_profile": "https://wordpress.stackexchange.com/users/847",
"pm_score": 0,
"selected": false,
"text": "<p>But from your description it's <em>not</em> an URL to a gallery, but individual image of one. I would guess it shou... | 2016/09/06 | [
"https://wordpress.stackexchange.com/questions/238395",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102311/"
] | I'm converting an existing website to a WordPress theme. One of the pages is a gallery that uses JS `history.pushState` to create unique URLs for loading certain images.
E.g. page URL (non WP website): `http://www.good-deeds-day.org/gallery/`
URL for a certain image: `http://www.good-deeds-day.org/gallery/img-35`
I would like to preserve this functionality in WordPress. However, when loading the URL for a certain image, WordPress considers it as a different page and displays a 404 error.
Is there a way to configure WordPress or `.htaccess` so that when such image URLs are loaded it will keep the URL and load the gallery page, thus displaying the relevant image in the gallery page? | I ended up using add\_rewrite\_rule:
```
function bones_rewrite_rules() {
$gallery_page_id = 395;
add_rewrite_rule('^gallery/img-.*', 'index.php?page_id=' . $gallery_page_id, 'top');
}
add_action('init', 'bones_rewrite_rules');
``` |
238,403 | <p>Creating first wp plugin.</p>
<p>Using add action init with filter for the_content</p>
<p>I noticed that whenever I echo anything it appears twice in the header, and finally once in the body.</p>
<p>Why?</p>
<p>Or How can I avoid this?</p>
<p>kthxbai</p>
<p><strong>EDIT</strong> </p>
<pre><code>function my_module_init() {
//Filter this content
add_filter('the_content', 'my_content_ctrlr');
}
add_action('init', 'my_module_init');
// function controller plug-in
function my_content_ctrlr($content) {
global $post;
//Get value of metabox from current id
$codeUnit = get_post_meta($post->ID, 'list_unit_meta_key', true);
//If none selected from metabox, skip it as its a regular page
if( $codeUnit == 'NULL' || !isset($codeUnit) || $codeUnit == '') {
return $content;
}
//if I add echo anything, it shows up twice in head and once in body
// WHY?
//echo $codeUnit;
ob_start();
//If photo included display grid view, else table view
if ($includePhoto == 'on') {
include(plugin_dir_path(__FILE__) . 'views/my-grid.php');
} else {
include(plugin_dir_path(__FILE__) . 'views/my-table.php');
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
</code></pre>
| [
{
"answer_id": 238438,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>I do not believe that the root issue exists within the code provided. I tested an even further reduced test ... | 2016/09/06 | [
"https://wordpress.stackexchange.com/questions/238403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87622/"
] | Creating first wp plugin.
Using add action init with filter for the\_content
I noticed that whenever I echo anything it appears twice in the header, and finally once in the body.
Why?
Or How can I avoid this?
kthxbai
**EDIT**
```
function my_module_init() {
//Filter this content
add_filter('the_content', 'my_content_ctrlr');
}
add_action('init', 'my_module_init');
// function controller plug-in
function my_content_ctrlr($content) {
global $post;
//Get value of metabox from current id
$codeUnit = get_post_meta($post->ID, 'list_unit_meta_key', true);
//If none selected from metabox, skip it as its a regular page
if( $codeUnit == 'NULL' || !isset($codeUnit) || $codeUnit == '') {
return $content;
}
//if I add echo anything, it shows up twice in head and once in body
// WHY?
//echo $codeUnit;
ob_start();
//If photo included display grid view, else table view
if ($includePhoto == 'on') {
include(plugin_dir_path(__FILE__) . 'views/my-grid.php');
} else {
include(plugin_dir_path(__FILE__) . 'views/my-table.php');
}
$output = ob_get_contents();
ob_end_clean();
return $output;
}
``` | I do not believe that the root issue exists within the code provided. I tested an even further reduced test case which I've pasted below, and I do not get duplicated content:
```
function my_module_init() {
add_filter('the_content', 'my_content_ctrlr');
}
add_action('init', 'my_module_init');
function my_content_ctrlr( $content ) {
ob_start();
// This file contains only the following simple text for testing purposes: #########
include( plugin_dir_path( __FILE__ ) . 'views/my-grid.php' );
$output = ob_get_contents();
ob_end_clean();
// Add our custom code before the existing content.
return $output . $content;
}
```
So, I think that we can rule out my original idea that content was being echoed instead of returned.
Another possibility is that there are additional `apply_filters()` calls on `the_content` somewhere in your site via plugins or the theme. E.g.:
```
echo ( apply_filters( 'the_content', '<div>Hello there!</div>' ) );
```
It's not uncommon for themes to do that kind of thing, and it would result in `my_content_ctrlr()` being called once for each additional occurrence.
You can use some additional checks as illustrated by this snippet to resolve that problem ([source](https://pippinsplugins.com/playing-nice-with-the-content-filter/)).
```
function pippin_filter_content_sample($content) {
if( is_singular() && is_main_query() ) {
$new_content = '<p>This is added to the bottom of all post and page content, as well as custom post types.</p>';
$content .= $new_content;
}
return $content;
}
add_filter('the_content', 'pippin_filter_content_sample');
``` |
238,422 | <p>As a plugin developer, I want to ensure that my plugin doesn't leave any custom settings left behind from my plugin when upgrading from <code>v1.0</code> to <code>v2.0</code>.</p>
<p>Whenever a user uninstalls my plugin, I've created an <a href="https://developer.wordpress.org/plugins/the-basics/uninstall-methods/" rel="nofollow"><code>uninstall.php</code></a> file (standard practice) which automatically removes all of my plugin's settings for a clean removal:</p>
<pre><code>if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) { // Exit if accessed directly
exit;
}
// Remove all plugin options with the prefix "myplugin_"
global $wpdb;
$plugin_options = $wpdb -> get_results( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE 'myplugin_%'" );
foreach( $plugin_options as $option ) {
delete_option( $option -> option_name );
}
</code></pre>
<p>This script automatically removes all options that have the prefix of <code>myplugin_</code> such as:</p>
<pre><code>myplugin_some_option
myplugin_another_option_here
myplugin_yup_this_one_too
etc...
</code></pre>
<p>However, I am already working on a new version of my plugin with new options in my settings page. If a user has an older version of my plugin and is upgrading to the next version without uninstalling it, how do I ensure all of my old plugin options are removed for a clean upgrade? Does the <code>uninstall.php</code> file automatically run when a user is upgrading to a new version of my plugin?</p>
| [
{
"answer_id": 238438,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>I do not believe that the root issue exists within the code provided. I tested an even further reduced test ... | 2016/09/06 | [
"https://wordpress.stackexchange.com/questions/238422",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98212/"
] | As a plugin developer, I want to ensure that my plugin doesn't leave any custom settings left behind from my plugin when upgrading from `v1.0` to `v2.0`.
Whenever a user uninstalls my plugin, I've created an [`uninstall.php`](https://developer.wordpress.org/plugins/the-basics/uninstall-methods/) file (standard practice) which automatically removes all of my plugin's settings for a clean removal:
```
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) { // Exit if accessed directly
exit;
}
// Remove all plugin options with the prefix "myplugin_"
global $wpdb;
$plugin_options = $wpdb -> get_results( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE 'myplugin_%'" );
foreach( $plugin_options as $option ) {
delete_option( $option -> option_name );
}
```
This script automatically removes all options that have the prefix of `myplugin_` such as:
```
myplugin_some_option
myplugin_another_option_here
myplugin_yup_this_one_too
etc...
```
However, I am already working on a new version of my plugin with new options in my settings page. If a user has an older version of my plugin and is upgrading to the next version without uninstalling it, how do I ensure all of my old plugin options are removed for a clean upgrade? Does the `uninstall.php` file automatically run when a user is upgrading to a new version of my plugin? | I do not believe that the root issue exists within the code provided. I tested an even further reduced test case which I've pasted below, and I do not get duplicated content:
```
function my_module_init() {
add_filter('the_content', 'my_content_ctrlr');
}
add_action('init', 'my_module_init');
function my_content_ctrlr( $content ) {
ob_start();
// This file contains only the following simple text for testing purposes: #########
include( plugin_dir_path( __FILE__ ) . 'views/my-grid.php' );
$output = ob_get_contents();
ob_end_clean();
// Add our custom code before the existing content.
return $output . $content;
}
```
So, I think that we can rule out my original idea that content was being echoed instead of returned.
Another possibility is that there are additional `apply_filters()` calls on `the_content` somewhere in your site via plugins or the theme. E.g.:
```
echo ( apply_filters( 'the_content', '<div>Hello there!</div>' ) );
```
It's not uncommon for themes to do that kind of thing, and it would result in `my_content_ctrlr()` being called once for each additional occurrence.
You can use some additional checks as illustrated by this snippet to resolve that problem ([source](https://pippinsplugins.com/playing-nice-with-the-content-filter/)).
```
function pippin_filter_content_sample($content) {
if( is_singular() && is_main_query() ) {
$new_content = '<p>This is added to the bottom of all post and page content, as well as custom post types.</p>';
$content .= $new_content;
}
return $content;
}
add_filter('the_content', 'pippin_filter_content_sample');
``` |
238,461 | <p>I'm using the Toolset Types plugin to create various custom posts and custom taxonomies. </p>
<p>I have 2 custom post types (Schools, and Productions) that share a common taxonomy (School Subjects). However, on the Schools edit page, I want the title of that taxonomy meta box to say "Subject Wishlist", while leaving the default title on the Productions edit page. So I can't just rename the taxonomy as a whole, because that would change it everywhere.</p>
<p>Any ideas? I have considered the various other answers here covering removing and re-adding metaboxes (eg <a href="https://wordpress.stackexchange.com/questions/39446/change-the-title-of-a-meta-box">this answer</a>). I'm concerned that may not work though, since the Toolset Types plugin generates these metaboxes dynamically (I think?)...</p>
| [
{
"answer_id": 238560,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>There is a filter called <code>register_taxonomy_args</code> in WP v4.4 that's a big help here. This tested ... | 2016/09/07 | [
"https://wordpress.stackexchange.com/questions/238461",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1118/"
] | I'm using the Toolset Types plugin to create various custom posts and custom taxonomies.
I have 2 custom post types (Schools, and Productions) that share a common taxonomy (School Subjects). However, on the Schools edit page, I want the title of that taxonomy meta box to say "Subject Wishlist", while leaving the default title on the Productions edit page. So I can't just rename the taxonomy as a whole, because that would change it everywhere.
Any ideas? I have considered the various other answers here covering removing and re-adding metaboxes (eg [this answer](https://wordpress.stackexchange.com/questions/39446/change-the-title-of-a-meta-box)). I'm concerned that may not work though, since the Toolset Types plugin generates these metaboxes dynamically (I think?)... | There is a filter called `register_taxonomy_args` in WP v4.4 that's a big help here. This tested and working example assumes that the post types `schools` and `productions` have already been created.
```
/**
* Filter the arguments for registering a taxonomy.
*
* @since 4.4.0
*
* @param array $args Array of arguments for registering a taxonomy.
* @param string $taxonomy Taxonomy key.
* @param array $object_type Array of names of object types for the taxonomy.
*/
add_filter( 'register_taxonomy_args', 'wpse238461_taxonomy_school_subjects_title_changer', 10, 3 );
function wpse238461_taxonomy_school_subjects_title_changer( $args, $taxonomy, $object_type ) {
// We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.
if ( ! isset( $_GET['post_type'] ) || ! $_GET['post_type'] ) {
return $args;
}
$post_type = $_GET['post_type'];
/*
// Bonus code for anyone trying to do this on regular post or page edit screens,
// $_GET['post_type'] is not set, so do something like this instead of/in addition to the above check
// We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.
if ( ! isset( $_GET['post'] ) || ! $_GET['post'] ) {
return $args;
}
// Get the post type (post or page), bail if we can't.
$post_type = get_post_type( $_GET['post'] );
if ( ! $post_type ) {
return $args;
}
*/
// Make sure we're looking at the right taxonomy since this filter runs for all of them.
if ( 'school_subjects' !== $taxonomy ) {
return $args;
}
// Check if we're viewing the appropriate post type, and modify the label.
if ( 'schools' === $post_type ) {
$args['labels']['name'] = _x( 'Subject Wishlists', 'taxonomy general name', 'textdomain' );
// Alternate example for when taxonomy is using the label argument instead of the entire labels argument:
// $args['label'] = 'Subject Wishlist';
}
return $args;
}
// Taxonomy registration code
add_action( 'init', 'create_taxonomy_school_subjects' );
function create_taxonomy_school_subjects() {
register_taxonomy(
'school_subjects',
array( 'schools', 'productions' ),
array(
//'label' => __( 'School Subjects' ),
'labels' => array(
'name' => _x( 'School Subjects', 'taxonomy general name', 'textdomain' ),
'singular_name' => _x( 'School Subject', 'taxonomy singular name', 'textdomain' ),
'search_items' => __( 'Search School Subjects', 'textdomain' ),
'all_items' => __( 'All School Subjects', 'textdomain' ),
'parent_item' => __( 'Parent School Subject', 'textdomain' ),
'parent_item_colon' => __( 'Parent School Subject:', 'textdomain' ),
'edit_item' => __( 'Edit School Subject', 'textdomain' ),
'update_item' => __( 'Update School Subject', 'textdomain' ),
'add_new_item' => __( 'Add New School Subject', 'textdomain' ),
'new_item_name' => __( 'New School Subject Name', 'textdomain' ),
'menu_name' => __( 'School Subjects', 'textdomain' ),
),
'rewrite' => array( 'slug' => 'school_subjects' ),
'hierarchical' => true,
)
);
}
```
School - Subject Wishlists
==========================
[](https://i.stack.imgur.com/DnqY4.png)
Production - School Subjects
============================
[](https://i.stack.imgur.com/dsKHd.png) |
238,477 | <p>I know we have the following command available in <code>WP-CLI</code> to remove transients</p>
<pre><code># Delete all transients
$ wp transient delete-all
</code></pre>
<p>However, my question is does it remove transients on all sites over multi sites? If not how can we remove transients on all sites?</p>
| [
{
"answer_id": 238560,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 2,
"selected": true,
"text": "<p>There is a filter called <code>register_taxonomy_args</code> in WP v4.4 that's a big help here. This tested ... | 2016/09/07 | [
"https://wordpress.stackexchange.com/questions/238477",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101396/"
] | I know we have the following command available in `WP-CLI` to remove transients
```
# Delete all transients
$ wp transient delete-all
```
However, my question is does it remove transients on all sites over multi sites? If not how can we remove transients on all sites? | There is a filter called `register_taxonomy_args` in WP v4.4 that's a big help here. This tested and working example assumes that the post types `schools` and `productions` have already been created.
```
/**
* Filter the arguments for registering a taxonomy.
*
* @since 4.4.0
*
* @param array $args Array of arguments for registering a taxonomy.
* @param string $taxonomy Taxonomy key.
* @param array $object_type Array of names of object types for the taxonomy.
*/
add_filter( 'register_taxonomy_args', 'wpse238461_taxonomy_school_subjects_title_changer', 10, 3 );
function wpse238461_taxonomy_school_subjects_title_changer( $args, $taxonomy, $object_type ) {
// We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.
if ( ! isset( $_GET['post_type'] ) || ! $_GET['post_type'] ) {
return $args;
}
$post_type = $_GET['post_type'];
/*
// Bonus code for anyone trying to do this on regular post or page edit screens,
// $_GET['post_type'] is not set, so do something like this instead of/in addition to the above check
// We'll need to figure out what kind of post type we're looking at, and it's too early for other methods.
if ( ! isset( $_GET['post'] ) || ! $_GET['post'] ) {
return $args;
}
// Get the post type (post or page), bail if we can't.
$post_type = get_post_type( $_GET['post'] );
if ( ! $post_type ) {
return $args;
}
*/
// Make sure we're looking at the right taxonomy since this filter runs for all of them.
if ( 'school_subjects' !== $taxonomy ) {
return $args;
}
// Check if we're viewing the appropriate post type, and modify the label.
if ( 'schools' === $post_type ) {
$args['labels']['name'] = _x( 'Subject Wishlists', 'taxonomy general name', 'textdomain' );
// Alternate example for when taxonomy is using the label argument instead of the entire labels argument:
// $args['label'] = 'Subject Wishlist';
}
return $args;
}
// Taxonomy registration code
add_action( 'init', 'create_taxonomy_school_subjects' );
function create_taxonomy_school_subjects() {
register_taxonomy(
'school_subjects',
array( 'schools', 'productions' ),
array(
//'label' => __( 'School Subjects' ),
'labels' => array(
'name' => _x( 'School Subjects', 'taxonomy general name', 'textdomain' ),
'singular_name' => _x( 'School Subject', 'taxonomy singular name', 'textdomain' ),
'search_items' => __( 'Search School Subjects', 'textdomain' ),
'all_items' => __( 'All School Subjects', 'textdomain' ),
'parent_item' => __( 'Parent School Subject', 'textdomain' ),
'parent_item_colon' => __( 'Parent School Subject:', 'textdomain' ),
'edit_item' => __( 'Edit School Subject', 'textdomain' ),
'update_item' => __( 'Update School Subject', 'textdomain' ),
'add_new_item' => __( 'Add New School Subject', 'textdomain' ),
'new_item_name' => __( 'New School Subject Name', 'textdomain' ),
'menu_name' => __( 'School Subjects', 'textdomain' ),
),
'rewrite' => array( 'slug' => 'school_subjects' ),
'hierarchical' => true,
)
);
}
```
School - Subject Wishlists
==========================
[](https://i.stack.imgur.com/DnqY4.png)
Production - School Subjects
============================
[](https://i.stack.imgur.com/dsKHd.png) |
238,530 | <p>I have a custom <code>WP_Users_Query</code> that I have been using on a site.</p>
<p>It has worked fine for a while. I went to add some pagination to the query using the <code>number</code> parameter <a href="https://codex.wordpress.org/Class_Reference/WP_User_Query#Pagination_Parameters" rel="nofollow">as per the docs here</a>. But for some reason, when I add that parameter I get an SQL error, unless I set it to <code>-1</code> where it returns everything.</p>
<p>Here is my code that works:</p>
<pre><code>$user_fields = array( 'ID', 'display_name', 'user_email' );
$args = array(
'role__in' => array('Subcriber', 'Editor'),
'meta_query' => array(
array(
'key' => 'list_in_directory',
'value' => 1,
'compare' => '='
)
),
'fields' => $user_fields,
'paged' => get_query_var('paged')
); // End Args
if ($args){
$user_query = new WP_User_Query( $args );
}
</code></pre>
<p>If I add the line:<code>'number' => '2'</code> to my args array (I have tried it both as a string and an integer, both with the same result) I get this error in my log:</p>
<blockquote>
<p>WordPress database error You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near '-2, 2' at line 15 for query
<code>SELECT SQL_CALC_FOUND_ROWS wp_users.ID,wp_users.display_name,wp_users.user_email FROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) INNER JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) WHERE 1=1 AND (
(
(
( wp_usermeta.meta_key = 'list_in_directory' AND wp_usermeta.meta_value = '1' )
)
AND
(
(
( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%\"Subcriber\"%' )
OR
( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%\"Editor\"%' )
)
)
)
) ORDER BY user_login ASC LIMIT -2, 2 made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/pand/page-templates/membership-directory.php'), WP_User_Query->__construct, WP_User_Query->query</code></p>
</blockquote>
<p>Also, I have tried using different numbers in place of 2 all with the same result. The only time I don't get the error is if I set it to -1. Then it works just fine(but no pagination).</p>
<p>I'm scratching my head on this one so any help would be much appreciated!</p>
| [
{
"answer_id": 238504,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 3,
"selected": true,
"text": "<p><code>$_SERVER['REQUEST_URI']</code> is your only option. wordpress failed parsing the url so not much yo... | 2016/09/07 | [
"https://wordpress.stackexchange.com/questions/238530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102389/"
] | I have a custom `WP_Users_Query` that I have been using on a site.
It has worked fine for a while. I went to add some pagination to the query using the `number` parameter [as per the docs here](https://codex.wordpress.org/Class_Reference/WP_User_Query#Pagination_Parameters). But for some reason, when I add that parameter I get an SQL error, unless I set it to `-1` where it returns everything.
Here is my code that works:
```
$user_fields = array( 'ID', 'display_name', 'user_email' );
$args = array(
'role__in' => array('Subcriber', 'Editor'),
'meta_query' => array(
array(
'key' => 'list_in_directory',
'value' => 1,
'compare' => '='
)
),
'fields' => $user_fields,
'paged' => get_query_var('paged')
); // End Args
if ($args){
$user_query = new WP_User_Query( $args );
}
```
If I add the line:`'number' => '2'` to my args array (I have tried it both as a string and an integer, both with the same result) I get this error in my log:
>
> WordPress database error You have an error in your SQL syntax;
> check the manual that corresponds to your MySQL server version for the right syntax to use near '-2, 2' at line 15 for query
> `SELECT SQL_CALC_FOUND_ROWS wp_users.ID,wp_users.display_name,wp_users.user_email FROM wp_users INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) INNER JOIN wp_usermeta AS mt1 ON ( wp_users.ID = mt1.user_id ) WHERE 1=1 AND (
> (
> (
> ( wp_usermeta.meta_key = 'list_in_directory' AND wp_usermeta.meta_value = '1' )
> )
> AND
> (
> (
> ( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%\"Subcriber\"%' )
> OR
> ( mt1.meta_key = 'wp_capabilities' AND mt1.meta_value LIKE '%\"Editor\"%' )
> )
> )
> )
> ) ORDER BY user_login ASC LIMIT -2, 2 made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/pand/page-templates/membership-directory.php'), WP_User_Query->__construct, WP_User_Query->query`
>
>
>
Also, I have tried using different numbers in place of 2 all with the same result. The only time I don't get the error is if I set it to -1. Then it works just fine(but no pagination).
I'm scratching my head on this one so any help would be much appreciated! | `$_SERVER['REQUEST_URI']` is your only option. wordpress failed parsing the url so not much you can get from the API |
238,535 | <p>I'm using the <a href="https://wordpress.org/plugins/cpt-onomies/" rel="nofollow">CPT-onomies plugin</a> to make a CPT into a taxonomy. I have a hero image CPT (created with <em>CPT-onomies</em>) and the hero images post type is attached to the page post type. This allows me to select a hero image post that will be a term of a page post. All of this is working fine. When I visit the page with the hero image as a taxonomy the hero image appears as desired.</p>
<p>What I'm trying to accomplish is that if I'm on a page whose ancestor has a hero image attached, I want the page to show the hero image attached to the parent. Below is my code. I get an array of ancestors and iterate through the array. The image shows up as desired but above the image this error appears:</p>
<blockquote>
<p><strong>Notice: Undefined property</strong>: <code>stdClass::$data</code> in <code>.../wp-includes/category-template.php</code> on <em>line 1176</em></p>
</blockquote>
<pre><code>//Get the current Post ID
$current_post_id = get_the_id();
//Get the current Post's ancestor's ID's
$current_post_parents = get_ancestors($current_post_id, 'page');
foreach ( $current_post_parents as $post_parent ) {
//If a hero image ID is associated with the current post being viewed (or a parent post of the current post) assign that hero image ID value to $hero_image_id
$hero_image_id = isset( $post_parent ) && ( $assigned_hero_images = get_the_terms( $post_parent, 'hero_images' ) ) && is_array( $assigned_hero_images ) && ( $hero_image = array_shift( $assigned_hero_images ) ) && isset( $hero_image->term_id ) ? $hero_image->term_id : NULL;
if ($hero_image_id)
break;
} //Code follows that displays the image based on the $hero_image_id
</code></pre>
<p>It's the <code>get_the_terms()</code> function that's throwing the error. Line 1176 of the <code>category-template.php</code> file is <code>$to_cache[ $key ] = $term->data;</code></p>
<p>To be clear, the notice only appears when I'm visiting a child page whose ancestor has a hero image attached. If I'm visiting the page on which the hero image is attached or visiting a page with no hero image attached on the page or any ancestor page then no error appears.</p>
| [
{
"answer_id": 238543,
"author": "Jeremy Ross",
"author_id": 102007,
"author_profile": "https://wordpress.stackexchange.com/users/102007",
"pm_score": 0,
"selected": false,
"text": "<p>I think the problem lies with this line:</p>\n\n<p><code>$hero_image_id = isset( $post_parent ) &&a... | 2016/09/07 | [
"https://wordpress.stackexchange.com/questions/238535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83438/"
] | I'm using the [CPT-onomies plugin](https://wordpress.org/plugins/cpt-onomies/) to make a CPT into a taxonomy. I have a hero image CPT (created with *CPT-onomies*) and the hero images post type is attached to the page post type. This allows me to select a hero image post that will be a term of a page post. All of this is working fine. When I visit the page with the hero image as a taxonomy the hero image appears as desired.
What I'm trying to accomplish is that if I'm on a page whose ancestor has a hero image attached, I want the page to show the hero image attached to the parent. Below is my code. I get an array of ancestors and iterate through the array. The image shows up as desired but above the image this error appears:
>
> **Notice: Undefined property**: `stdClass::$data` in `.../wp-includes/category-template.php` on *line 1176*
>
>
>
```
//Get the current Post ID
$current_post_id = get_the_id();
//Get the current Post's ancestor's ID's
$current_post_parents = get_ancestors($current_post_id, 'page');
foreach ( $current_post_parents as $post_parent ) {
//If a hero image ID is associated with the current post being viewed (or a parent post of the current post) assign that hero image ID value to $hero_image_id
$hero_image_id = isset( $post_parent ) && ( $assigned_hero_images = get_the_terms( $post_parent, 'hero_images' ) ) && is_array( $assigned_hero_images ) && ( $hero_image = array_shift( $assigned_hero_images ) ) && isset( $hero_image->term_id ) ? $hero_image->term_id : NULL;
if ($hero_image_id)
break;
} //Code follows that displays the image based on the $hero_image_id
```
It's the `get_the_terms()` function that's throwing the error. Line 1176 of the `category-template.php` file is `$to_cache[ $key ] = $term->data;`
To be clear, the notice only appears when I'm visiting a child page whose ancestor has a hero image attached. If I'm visiting the page on which the hero image is attached or visiting a page with no hero image attached on the page or any ancestor page then no error appears. | I ended up using the `wp_get_object_terms()` function instead of `get_the_terms()`. The `get_the_terms()` function attempts to cache the terms where `wp_get_object_terms()` does not.
The fixed code to get the hero images CPT's ID is:
```
$hero_image_id = ( $assigned_hero_images = wp_get_object_terms( $post_parent, 'hero_images' ) ) && ( $hero_image = array_shift( $assigned_hero_images ) ) && isset( $hero_image->term_id ) ? $hero_image->term_id : NULL;
``` |
238,547 | <p>I want to dequeue a script ('enterprise-responsive-menu'), but the function I have in my template does not do that. Does anything look wrong? </p>
<p>Here is the enqueue in functions.php-</p>
<pre><code>//* Enqueue Scripts
add_action( 'wp_enqueue_scripts', 'enterprise_load_scripts' );
function enterprise_load_scripts() {
wp_enqueue_script( 'enterprise-responsive-menu', get_bloginfo( 'stylesheet_directory' ) . '/js/responsive-menu.js', array( 'jquery' ), '1.0.0' );
wp_enqueue_style( 'dashicons' );
wp_enqueue_style( 'google-fonts', '//fonts.googleapis.com/css?family=Lato:300,700,300italic|Titillium+Web:600', array(), CHILD_THEME_VERSION );
}'
</code></pre>
<p>Here is the dequeue code in my template -</p>
<pre><code>//Remove Mobile Header
function project_dequeue_unnecessary_scripts() {
wp_dequeue_script( 'enterprise-responsive-menu' );
wp_deregister_script( 'enterprise-responsive-menu' );
}
add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );
</code></pre>
| [
{
"answer_id": 238549,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Move your <code>project_dequeue_unnecessary_scripts()</code> function to your <code>functions.php</code> fil... | 2016/09/07 | [
"https://wordpress.stackexchange.com/questions/238547",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102397/"
] | I want to dequeue a script ('enterprise-responsive-menu'), but the function I have in my template does not do that. Does anything look wrong?
Here is the enqueue in functions.php-
```
//* Enqueue Scripts
add_action( 'wp_enqueue_scripts', 'enterprise_load_scripts' );
function enterprise_load_scripts() {
wp_enqueue_script( 'enterprise-responsive-menu', get_bloginfo( 'stylesheet_directory' ) . '/js/responsive-menu.js', array( 'jquery' ), '1.0.0' );
wp_enqueue_style( 'dashicons' );
wp_enqueue_style( 'google-fonts', '//fonts.googleapis.com/css?family=Lato:300,700,300italic|Titillium+Web:600', array(), CHILD_THEME_VERSION );
}'
```
Here is the dequeue code in my template -
```
//Remove Mobile Header
function project_dequeue_unnecessary_scripts() {
wp_dequeue_script( 'enterprise-responsive-menu' );
wp_deregister_script( 'enterprise-responsive-menu' );
}
add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );
``` | Move your `project_dequeue_unnecessary_scripts()` function to your `functions.php` file and add a conditional statement to determine if the appropriate template is being loaded. E.g.:
```
// Remove Mobile Header
function project_dequeue_unnecessary_scripts() {
if ( is_page_template( 'name-of-template.php' ) ) {
wp_dequeue_script( 'enterprise-responsive-menu' );
wp_deregister_script( 'enterprise-responsive-menu' );
}
}
add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );
```
I suspect that your function is not working because it has been placed somewhere after the call to `get_header()` in the template file which means it would be too late to dequeue the script. Declaring functions in template files is not a good practice anyway, so use your `functions.php` file or another include. |
238,555 | <p>I set up and configured a WordPress site using WooCommerce. When I was developing, I imported the dummy data for testing.</p>
<p>How can I remove the dummy data to delivery?</p>
| [
{
"answer_id": 238549,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 3,
"selected": true,
"text": "<p>Move your <code>project_dequeue_unnecessary_scripts()</code> function to your <code>functions.php</code> fil... | 2016/09/08 | [
"https://wordpress.stackexchange.com/questions/238555",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83673/"
] | I set up and configured a WordPress site using WooCommerce. When I was developing, I imported the dummy data for testing.
How can I remove the dummy data to delivery? | Move your `project_dequeue_unnecessary_scripts()` function to your `functions.php` file and add a conditional statement to determine if the appropriate template is being loaded. E.g.:
```
// Remove Mobile Header
function project_dequeue_unnecessary_scripts() {
if ( is_page_template( 'name-of-template.php' ) ) {
wp_dequeue_script( 'enterprise-responsive-menu' );
wp_deregister_script( 'enterprise-responsive-menu' );
}
}
add_action( 'wp_print_scripts', 'project_dequeue_unnecessary_scripts' );
```
I suspect that your function is not working because it has been placed somewhere after the call to `get_header()` in the template file which means it would be too late to dequeue the script. Declaring functions in template files is not a good practice anyway, so use your `functions.php` file or another include. |
238,587 | <p>I am configuring Git along with my WP development environment, and I was wondering what should be tracked and what should be ignored. If it makes sense to track plugins and for WP core. Create one repo for both theme & plugins?</p>
<p>Common sense would suggest that tracking WP as a whole, is overkill and unuseful, as I am not involved in core development and updates; of course, I want to track my theme/child-theme folder where my work is. Plugins?</p>
<p>So I wonder what is the suggested setup, how many repositories and what to track/ignore</p>
<p>References:</p>
<p><a href="https://wordpress.stackexchange.com/questions/128164/how-should-i-structure-a-wp-website-project-using-git-and-updating-from-wp-dashb">How should I structure a WP website project using git and updating from WP dashboard?</a></p>
<p><a href="https://wordpress.stackexchange.com/questions/205999/what-is-the-best-way-to-setup-wordpress-development-environment-for-freelancers">What is the best way to setup wordpress development environment for freelancers with version control?</a></p>
| [
{
"answer_id": 238592,
"author": "Kenya Sullivan",
"author_id": 92563,
"author_profile": "https://wordpress.stackexchange.com/users/92563",
"pm_score": 2,
"selected": false,
"text": "<p>This is subjective and depends on what you are trying to achieve. A theme developer may have a differe... | 2016/09/08 | [
"https://wordpress.stackexchange.com/questions/238587",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1210/"
] | I am configuring Git along with my WP development environment, and I was wondering what should be tracked and what should be ignored. If it makes sense to track plugins and for WP core. Create one repo for both theme & plugins?
Common sense would suggest that tracking WP as a whole, is overkill and unuseful, as I am not involved in core development and updates; of course, I want to track my theme/child-theme folder where my work is. Plugins?
So I wonder what is the suggested setup, how many repositories and what to track/ignore
References:
[How should I structure a WP website project using git and updating from WP dashboard?](https://wordpress.stackexchange.com/questions/128164/how-should-i-structure-a-wp-website-project-using-git-and-updating-from-wp-dashb)
[What is the best way to setup wordpress development environment for freelancers with version control?](https://wordpress.stackexchange.com/questions/205999/what-is-the-best-way-to-setup-wordpress-development-environment-for-freelancers) | Basically ignore everything except your theme folder and custom plugins. sample .gitignore:
```
wp-admin/
wp-includes/
.htaccess
index.php
license.txt
liesmich.html
readme.html
wp-activate.php
wp-blog-header.php
wp-comments-post.php
wp-config.php
wp-config-sample.php
wp-config-stage.php
wp-config-live.php
wp-config-dev.php
wp-config-production.php
wp-cron.php
wp-links-opml.php
wp-load.php
wp-login.php
wp-mail.php
wp-settings.php
wp-signup.php
wp-trackback.php
xmlrpc.php
config/
wp-content/plugins/
wp-content/mu-plugins/
wp-content/languages/
wp-content/uploads/
wp-content/upgrade/
wp-content/themes/*
# don't ignore the theme you're using
!wp-content/themes/yourthemename
```
This makes the most sense when used together with composer for installing wordpress and plugins. |
238,589 | <p>I have several categories post:</p>
<pre><code>General
News
Comedy
Competitions
Culture
Gaming
Food
etc
</code></pre>
<p>The posts url are in the following format:</p>
<pre><code>www.mydomain.com/category-name/post-title
</code></pre>
<p>Example:</p>
<pre><code>www.mydomain.com/food/how-to-make-paella
www.mydomain.com/gaming/game-of-theday
</code></pre>
<p>But I would like to hide from the URL the category name 'general' so for example.</p>
<p>instead of </p>
<pre><code>www.mydomain.com/general/how-to-learn-spanish
</code></pre>
<p>have</p>
<pre><code>www.mydomain.com/how-to-learn-spanish
</code></pre>
<p>I have tried some wiring a rewrite rule in the .htaccess but doesn't work.</p>
<p>Any idea how can I do it?</p>
<p>Thanks!</p>
| [
{
"answer_id": 238592,
"author": "Kenya Sullivan",
"author_id": 92563,
"author_profile": "https://wordpress.stackexchange.com/users/92563",
"pm_score": 2,
"selected": false,
"text": "<p>This is subjective and depends on what you are trying to achieve. A theme developer may have a differe... | 2016/09/08 | [
"https://wordpress.stackexchange.com/questions/238589",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65640/"
] | I have several categories post:
```
General
News
Comedy
Competitions
Culture
Gaming
Food
etc
```
The posts url are in the following format:
```
www.mydomain.com/category-name/post-title
```
Example:
```
www.mydomain.com/food/how-to-make-paella
www.mydomain.com/gaming/game-of-theday
```
But I would like to hide from the URL the category name 'general' so for example.
instead of
```
www.mydomain.com/general/how-to-learn-spanish
```
have
```
www.mydomain.com/how-to-learn-spanish
```
I have tried some wiring a rewrite rule in the .htaccess but doesn't work.
Any idea how can I do it?
Thanks! | Basically ignore everything except your theme folder and custom plugins. sample .gitignore:
```
wp-admin/
wp-includes/
.htaccess
index.php
license.txt
liesmich.html
readme.html
wp-activate.php
wp-blog-header.php
wp-comments-post.php
wp-config.php
wp-config-sample.php
wp-config-stage.php
wp-config-live.php
wp-config-dev.php
wp-config-production.php
wp-cron.php
wp-links-opml.php
wp-load.php
wp-login.php
wp-mail.php
wp-settings.php
wp-signup.php
wp-trackback.php
xmlrpc.php
config/
wp-content/plugins/
wp-content/mu-plugins/
wp-content/languages/
wp-content/uploads/
wp-content/upgrade/
wp-content/themes/*
# don't ignore the theme you're using
!wp-content/themes/yourthemename
```
This makes the most sense when used together with composer for installing wordpress and plugins. |
238,600 | <p>I have comments enabled on my site but the form isn't appearing. It worked at one point as there are comments on some of my posts with links to them but they don't appear on the page.</p>
<p>Take this post: <a href="https://arcath.net/2016/03/react/" rel="noreferrer">https://arcath.net/2016/03/react/</a> The theme is clearly showing 1 comment at the top of the page.</p>
<p>Comments are enabled in <code>Settings -> Discussion</code></p>
<p><a href="https://i.stack.imgur.com/YjNpc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YjNpc.png" alt="Discussion Settings"></a></p>
<p><a href="https://i.stack.imgur.com/xrxb3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xrxb3.png" alt="Post Options"></a></p>
<p>I've read a lot of forum posts on the subject that lead me to these settings but I can't see anything wrong with them.</p>
| [
{
"answer_id": 238602,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Stupid question :</strong> \nIs it possible that your theme doesn't include the comments on display... | 2016/09/08 | [
"https://wordpress.stackexchange.com/questions/238600",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85357/"
] | I have comments enabled on my site but the form isn't appearing. It worked at one point as there are comments on some of my posts with links to them but they don't appear on the page.
Take this post: <https://arcath.net/2016/03/react/> The theme is clearly showing 1 comment at the top of the page.
Comments are enabled in `Settings -> Discussion`
[](https://i.stack.imgur.com/YjNpc.png)
[](https://i.stack.imgur.com/xrxb3.png)
I've read a lot of forum posts on the subject that lead me to these settings but I can't see anything wrong with them. | **Stupid question :**
Is it possible that your theme doesn't include the comments on display?
In addition to settings, your theme must display comments.
The default function provided by WP is [comments\_template](https://developer.wordpress.org/reference/functions/comments_template/) (to use on single.php and/or page.php) :
```
comments_template( '', true );
```
**UPDATE ---------------------------------------------------**
I believe there is something wrong with the theme "hueman".
I installed it on a local WP containing sample contents.
When I go to an article containing comments, I have the exact same result as you get.
If I display the exact same article using a different theme (one of the defaults provided), the comments are displayed.
So I checked the single.php template file of the hueman theme and it use a custom function ( hu\_is\_checked('post-comments') ).
Used in:
```
if ( hu_is_checked('post-comments') ) { comments_template('/comments.php',true); }
```
The problem is: it return null (so the comments can't be displayed).
According to the theme documentation, we should be able to customize the theme options through the customizer
<http://docs.presscustomizr.com/article/113-customizr-theme-options-comments>
This option is located in : Customizer > Content Panel > Comments
Unfortunatly I wasn't able to found it :
I tried on front page, single post, page, never saw it.
So, since the option is not defined, the custom function will always return null.
A quick fix would be to create a child theme of hueman, overwrite single.php template and change the line for:
```
comments_template('/comments.php',true);
```
I tested it, it works.
A better solution would be to contact the theme author to see if we missed something or if it's a bug. |
238,606 | <p>I created a custom table 'products' with the following field:title,description,url.The items stored into the table are imported.</p>
<p>I would like to extends the wordpress search to this table.
Is it possible to do this?</p>
| [
{
"answer_id": 238602,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Stupid question :</strong> \nIs it possible that your theme doesn't include the comments on display... | 2016/09/08 | [
"https://wordpress.stackexchange.com/questions/238606",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102441/"
] | I created a custom table 'products' with the following field:title,description,url.The items stored into the table are imported.
I would like to extends the wordpress search to this table.
Is it possible to do this? | **Stupid question :**
Is it possible that your theme doesn't include the comments on display?
In addition to settings, your theme must display comments.
The default function provided by WP is [comments\_template](https://developer.wordpress.org/reference/functions/comments_template/) (to use on single.php and/or page.php) :
```
comments_template( '', true );
```
**UPDATE ---------------------------------------------------**
I believe there is something wrong with the theme "hueman".
I installed it on a local WP containing sample contents.
When I go to an article containing comments, I have the exact same result as you get.
If I display the exact same article using a different theme (one of the defaults provided), the comments are displayed.
So I checked the single.php template file of the hueman theme and it use a custom function ( hu\_is\_checked('post-comments') ).
Used in:
```
if ( hu_is_checked('post-comments') ) { comments_template('/comments.php',true); }
```
The problem is: it return null (so the comments can't be displayed).
According to the theme documentation, we should be able to customize the theme options through the customizer
<http://docs.presscustomizr.com/article/113-customizr-theme-options-comments>
This option is located in : Customizer > Content Panel > Comments
Unfortunatly I wasn't able to found it :
I tried on front page, single post, page, never saw it.
So, since the option is not defined, the custom function will always return null.
A quick fix would be to create a child theme of hueman, overwrite single.php template and change the line for:
```
comments_template('/comments.php',true);
```
I tested it, it works.
A better solution would be to contact the theme author to see if we missed something or if it's a bug. |
238,640 | <p>Looking through the <a href="https://developer.wordpress.org/reference/functions/is_page_template/" rel="noreferrer">Wordpress documentation</a>, it says that <code>is_page_template()</code> compares against a "template name", if one is provided.</p>
<p>I have a template stored in <code>page-homepage.php</code> called <code>Homepage</code>:</p>
<pre><code>/*
* Template Name: Homepage
* Description: The template for displaying the homepage
*/
</code></pre>
<p>And I have some code I wish to run in my functions.php when I'm using that template:</p>
<pre><code>if (is_page_template('Homepage')) {
...
</code></pre>
<p>But it isn't being triggered when I'm on a page which uses that template.</p>
<p>When I look at the code that Wordpress executes for <code>is_page_template()</code>, it looks like it actually checks for the document name, not the template name...?</p>
<pre><code>function is_page_template( $template = '' ) {
$page_template = get_page_template_slug( get_queried_object_id() );
if ( $template == $page_template )
return true;
</code></pre>
<p>In my instance it seems that <code>$page_template</code> is <code>page-homepage.php</code> -- not the template name, like the documentation suggests...?</p>
<p>Am I doing something wrong?</p>
| [
{
"answer_id": 238642,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 5,
"selected": true,
"text": "<p>Your condition should be written like this:</p>\n<pre><code>if (is_page_template('path/file.php')) { \n // ... | 2016/09/08 | [
"https://wordpress.stackexchange.com/questions/238640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4109/"
] | Looking through the [Wordpress documentation](https://developer.wordpress.org/reference/functions/is_page_template/), it says that `is_page_template()` compares against a "template name", if one is provided.
I have a template stored in `page-homepage.php` called `Homepage`:
```
/*
* Template Name: Homepage
* Description: The template for displaying the homepage
*/
```
And I have some code I wish to run in my functions.php when I'm using that template:
```
if (is_page_template('Homepage')) {
...
```
But it isn't being triggered when I'm on a page which uses that template.
When I look at the code that Wordpress executes for `is_page_template()`, it looks like it actually checks for the document name, not the template name...?
```
function is_page_template( $template = '' ) {
$page_template = get_page_template_slug( get_queried_object_id() );
if ( $template == $page_template )
return true;
```
In my instance it seems that `$page_template` is `page-homepage.php` -- not the template name, like the documentation suggests...?
Am I doing something wrong? | Your condition should be written like this:
```
if (is_page_template('path/file.php')) {
// Do stuff
}
```
I believe the confusion is a result of two things:
1. The docs refer to "name" ambiguously. Specifying "file name" would make the documentation much more clear.
2. The code behind `is_page_template()` shows the `get_page_template_slug()` function at its core. This function actually returns a file name, not the template slug. <https://codex.wordpress.org/Function_Reference/get_page_template_slug>
When specifying an argument for the `is_page_template()` function (as in the example above), the file path is relative to the theme root.
This function will not work inside the loop.
EDIT: an important issue to note here as well. The `is_page_template()` function will return empty/false if the page is using the default template from the hierarchy. If a custom template is not assigned, you must use another method, such as `basename(get_page_template())`. See Jacob's answer here for more details: <https://wordpress.stackexchange.com/a/328427/45202> |
238,645 | <p>I'm using the catch-base theme as a parent theme and have the following code in functions.php </p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = 'catch-base';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-theme',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style )
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
</code></pre>
<p>I for-the-life-of-me cannot figure out how to overwrite any of the template files through the child theme. I have tried the suggestion on the catchthemes website, <a href="https://catchthemes.com/blog/create-child-theme-wordpress/" rel="nofollow">https://catchthemes.com/blog/create-child-theme-wordpress/</a> but just using the same directory structure isn't working.</p>
<p>I've also tried adding this code after the "add_action" function, but it breaks the site and gives an "access denied" error.</p>
<pre><code>require_once( get_stylesheet_directory() . '/inc/catchbase-structure.php' );
</code></pre>
<p>What am I missing?</p>
| [
{
"answer_id": 238649,
"author": "Brandon",
"author_id": 102030,
"author_profile": "https://wordpress.stackexchange.com/users/102030",
"pm_score": 2,
"selected": false,
"text": "<p>The catch-base theme wraps every function in an if statement to make it easy to modify if necessary.</p>\n\... | 2016/09/08 | [
"https://wordpress.stackexchange.com/questions/238645",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102030/"
] | I'm using the catch-base theme as a parent theme and have the following code in functions.php
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'catch-base';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-theme',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style )
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
```
I for-the-life-of-me cannot figure out how to overwrite any of the template files through the child theme. I have tried the suggestion on the catchthemes website, <https://catchthemes.com/blog/create-child-theme-wordpress/> but just using the same directory structure isn't working.
I've also tried adding this code after the "add\_action" function, but it breaks the site and gives an "access denied" error.
```
require_once( get_stylesheet_directory() . '/inc/catchbase-structure.php' );
```
What am I missing? | The catch-base theme wraps every function in an if statement to make it easy to modify if necessary.
Example....
```
if (! function_exists('function_name')) {
/* some code */
}
```
So what I ended up doing was adding this to my functions.php file in the child theme and it overwrote the function and the extra divs that I added showed up!
```
function function_name() {
/* some modified code */
}
``` |
238,647 | <p>I have an anchor link on my product pages to a div further down the page. The div only shows if there is content in it.</p>
<p>Is it possible to write an if statement for the link based on the div ID? If #ID exists? </p>
<p>This is the div:</p>
<pre><code><div class="upsells products" id="tab-accessories">
<!--Change related products text-->
<?php
global $post;
//If Product Page is a Model page, display "Reccomended Accessories"
if ( has_term( 'Models', 'product_cat', $post->ID ) ) {
echo '<h2>' . 'Reccomended Accessories' . '</h2>';
}
//If Product Page is an Accessories page, display "Customers Also Bought"
if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {
echo '<h2>' . 'Customers Also Bought' . '</h2>';
}
?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
</div>
</code></pre>
<p>This is the link:</p>
<pre><code> <li><a href="#tab-accessories">Accessories</a></li>
</code></pre>
| [
{
"answer_id": 238694,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>You're approach this the wrong way, I think. Even before you are outputting the link and the div in your templat... | 2016/09/08 | [
"https://wordpress.stackexchange.com/questions/238647",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85805/"
] | I have an anchor link on my product pages to a div further down the page. The div only shows if there is content in it.
Is it possible to write an if statement for the link based on the div ID? If #ID exists?
This is the div:
```
<div class="upsells products" id="tab-accessories">
<!--Change related products text-->
<?php
global $post;
//If Product Page is a Model page, display "Reccomended Accessories"
if ( has_term( 'Models', 'product_cat', $post->ID ) ) {
echo '<h2>' . 'Reccomended Accessories' . '</h2>';
}
//If Product Page is an Accessories page, display "Customers Also Bought"
if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {
echo '<h2>' . 'Customers Also Bought' . '</h2>';
}
?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
</div>
```
This is the link:
```
<li><a href="#tab-accessories">Accessories</a></li>
``` | This can be done but we need to see the if statement that is around your div. Right now you that code above will still present the div, just not the content IN the div. You need to wrap that link code in the same if statement that your div is in.
example: if your div if statement is:
```
if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {
echo '<div class="upsells products" id="tab-accessories">CONTENT OF DIV</div>';
}
```
wrap your link earlier in the code with the same if statement:
```
if ( has_term( 'Accessories', 'product_cat', $post->ID ) ) {
echo '<li><a href="#tab-accessories">Accessories</a></li>';
}
```
whatever happens to one will be the same as the other. |
238,672 | <p>I've noticed plugins using a singleton pattern that will use WordPress's <code>_doing_it_wrong()</code> function in their <code>clone()</code> methods, like so:</p>
<pre><code><?php
public function __clone() {
_doing_it_wrong( __FUNCTION__, __( 'Cheatin&#8217; huh?', 'divlibrary' ), $this->version );
}
?>
</code></pre>
<p>But I also noticed this warning/notice on WordPress's official documentation:
<a href="https://i.stack.imgur.com/JViCx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JViCx.png" alt="enter image description here"></a></p>
<p>It really doesn't matter when, how a developer is using it, WordPress is advocating that it shouldn't be used, so I'm wondering what is the correct way to do this within custom plugins? The method is used for deprecating code but in this instance the developer is just wanting to send a warning/alert out.</p>
<p><strong>Reference:</strong> <a href="https://developer.wordpress.org/reference/functions/_doing_it_wrong/" rel="noreferrer">https://developer.wordpress.org/reference/functions/_doing_it_wrong/</a></p>
| [
{
"answer_id": 263996,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>What is an alternative method to the WordPress private _doing_it_wrong() function?</p... | 2016/09/09 | [
"https://wordpress.stackexchange.com/questions/238672",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12691/"
] | I've noticed plugins using a singleton pattern that will use WordPress's `_doing_it_wrong()` function in their `clone()` methods, like so:
```
<?php
public function __clone() {
_doing_it_wrong( __FUNCTION__, __( 'Cheatin’ huh?', 'divlibrary' ), $this->version );
}
?>
```
But I also noticed this warning/notice on WordPress's official documentation:
[](https://i.stack.imgur.com/JViCx.png)
It really doesn't matter when, how a developer is using it, WordPress is advocating that it shouldn't be used, so I'm wondering what is the correct way to do this within custom plugins? The method is used for deprecating code but in this instance the developer is just wanting to send a warning/alert out.
**Reference:** <https://developer.wordpress.org/reference/functions/_doing_it_wrong/> | >
> What is an alternative method to the WordPress private \_doing\_it\_wrong() function?
>
>
>
There's no way that WordPress is ever going to get rid of the `_doing_it_wrong()` function, so it's perfectly safe to use it. But if for some reason you don't want to use it because it's marked private, then you could create a plugin that has a function called `doing_it_wrong()` that is copy and pasted from `_doing_it_wrong()`.
Another way would be to not copy code and instead use a class that handles deprecated code. Here's some sample code that basically does the same thing as `_doing_it_wrong()`.
```
class deprecated {
protected $method;
protected $message;
protected $version;
public function method( $method ) {
$this->method = $method;
return $this;
}
public function message( $message ) {
$this->message = $message;
return $this;
}
public function version( $version ) {
$this->version = sprintf(
__( 'This message was added in version %1$s.' ),
$version
);
return $this;
}
public function trigger_error() {
do_action( 'doing_it_wrong_run', $this->method, $this->message, $this->version );
if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
trigger_error( sprintf(
__( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),
isset( $this->method ) ? $this->method : '',
isset( $this->message ) ? $this->message : '',
isset( $this->version ) ? $this->version : ''
) );
}
}
}
```
### Usage
```
class wpse_238672 {
public function some_deprecated_method() {
( new deprecated() )
->method( __METHOD__ )
->message( __(
'Deprecated Method: Use non_deprecated_method() instead.', 'wpse-238672'
) )
->version( '2.3.4' )
->trigger_error();
$this->non_deprecated_method();
}
public function non_deprecated_method() {
}
}
``` |
238,679 | <p>I've been working with the <code>wp_list_categories( $args );</code> to display categories from a taxonomy and I feel that this might be the wrong method to use. Now I'm wondering if it is possible to instead of having the categories outputted into an unordered list, they are outputted as individual div elements for each category. Is there a better alternative to doing this?</p>
<pre><code><?php
$args = array(
'show_option_none' => __( 'No treatment categories' ),
'taxonomy' => 'treatment-categories',
'title_li' => __( 'Treatment Categories' )
);
wp_list_categories( $args );
?>
</code></pre>
<p>My original prototype of the site is using a grid system with individual columns for each category.</p>
<p><a href="https://i.stack.imgur.com/DNI6T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DNI6T.png" alt="Original site prototype demonstrating what I need to accomplish"></a></p>
<p>I have worked with <code>get_categories( $args );</code> and I was able to accommplish what was expected, however I had an issue of trying to link to each category when a user would click on the 'View Treatment' button, it would take the user to the 404 page. Here was the template I was building when I was working with <code>get_categories( $args );</code>.</p>
<pre><code><?php get_header(); ?>
<section class="hero hero-sml hero-default no-marg-bottom">
<div class="container clearfix">
<h1>Treatments</h1>
</div><!-- .container -->
</section><!-- .hero -->
<section class="margin-top container clearfix">
<div class="row">
<?php
$args = array(
'taxonomy' => 'treatment-categories',
);
$categories = get_categories( $args );
foreach( $categories as $category ) {
?>
<div class="col-4 treatment-category">
<h3>
<?php echo $category->name; ?>
</h3>
<p>
<?php echo $category->description; ?>
</p>
<p>
<a class="btn btn-sml btn-clr btn-primary" href="<?php echo esc_url( $category_link ); ?>">
View treatments
</a>
</p>
</div><!-- .col-4 -->
<?php
}
?>
</div><!-- .row -->
</section><!-- .container -->
<?php get_footer(); ?>
</code></pre>
<p>Any help on how I can achieve this will be greatly appreciated as I've been stuck on this for a couple of weeks.</p>
| [
{
"answer_id": 263996,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>What is an alternative method to the WordPress private _doing_it_wrong() function?</p... | 2016/09/09 | [
"https://wordpress.stackexchange.com/questions/238679",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93077/"
] | I've been working with the `wp_list_categories( $args );` to display categories from a taxonomy and I feel that this might be the wrong method to use. Now I'm wondering if it is possible to instead of having the categories outputted into an unordered list, they are outputted as individual div elements for each category. Is there a better alternative to doing this?
```
<?php
$args = array(
'show_option_none' => __( 'No treatment categories' ),
'taxonomy' => 'treatment-categories',
'title_li' => __( 'Treatment Categories' )
);
wp_list_categories( $args );
?>
```
My original prototype of the site is using a grid system with individual columns for each category.
[](https://i.stack.imgur.com/DNI6T.png)
I have worked with `get_categories( $args );` and I was able to accommplish what was expected, however I had an issue of trying to link to each category when a user would click on the 'View Treatment' button, it would take the user to the 404 page. Here was the template I was building when I was working with `get_categories( $args );`.
```
<?php get_header(); ?>
<section class="hero hero-sml hero-default no-marg-bottom">
<div class="container clearfix">
<h1>Treatments</h1>
</div><!-- .container -->
</section><!-- .hero -->
<section class="margin-top container clearfix">
<div class="row">
<?php
$args = array(
'taxonomy' => 'treatment-categories',
);
$categories = get_categories( $args );
foreach( $categories as $category ) {
?>
<div class="col-4 treatment-category">
<h3>
<?php echo $category->name; ?>
</h3>
<p>
<?php echo $category->description; ?>
</p>
<p>
<a class="btn btn-sml btn-clr btn-primary" href="<?php echo esc_url( $category_link ); ?>">
View treatments
</a>
</p>
</div><!-- .col-4 -->
<?php
}
?>
</div><!-- .row -->
</section><!-- .container -->
<?php get_footer(); ?>
```
Any help on how I can achieve this will be greatly appreciated as I've been stuck on this for a couple of weeks. | >
> What is an alternative method to the WordPress private \_doing\_it\_wrong() function?
>
>
>
There's no way that WordPress is ever going to get rid of the `_doing_it_wrong()` function, so it's perfectly safe to use it. But if for some reason you don't want to use it because it's marked private, then you could create a plugin that has a function called `doing_it_wrong()` that is copy and pasted from `_doing_it_wrong()`.
Another way would be to not copy code and instead use a class that handles deprecated code. Here's some sample code that basically does the same thing as `_doing_it_wrong()`.
```
class deprecated {
protected $method;
protected $message;
protected $version;
public function method( $method ) {
$this->method = $method;
return $this;
}
public function message( $message ) {
$this->message = $message;
return $this;
}
public function version( $version ) {
$this->version = sprintf(
__( 'This message was added in version %1$s.' ),
$version
);
return $this;
}
public function trigger_error() {
do_action( 'doing_it_wrong_run', $this->method, $this->message, $this->version );
if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
trigger_error( sprintf(
__( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ),
isset( $this->method ) ? $this->method : '',
isset( $this->message ) ? $this->message : '',
isset( $this->version ) ? $this->version : ''
) );
}
}
}
```
### Usage
```
class wpse_238672 {
public function some_deprecated_method() {
( new deprecated() )
->method( __METHOD__ )
->message( __(
'Deprecated Method: Use non_deprecated_method() instead.', 'wpse-238672'
) )
->version( '2.3.4' )
->trigger_error();
$this->non_deprecated_method();
}
public function non_deprecated_method() {
}
}
``` |
238,680 | <p>I am using following codes to show title of a post in another post.But it shows only post id.How to solve this?</p>
<pre><code><?php $home_team_name = rwmb_meta( 'pb_select_home_team', 'type=select_advanced', get_the_ID() ); ?>
<?php echo esc_html( $home_team_name ); ?>
</code></pre>
<p>Thanks</p>
| [
{
"answer_id": 238681,
"author": "user3114253",
"author_id": 76325,
"author_profile": "https://wordpress.stackexchange.com/users/76325",
"pm_score": 0,
"selected": false,
"text": "<p>Generally we use <code>the_title()</code> or <code>echo get_the_title()</code> to print title</p>\n\n<p>t... | 2016/09/09 | [
"https://wordpress.stackexchange.com/questions/238680",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83330/"
] | I am using following codes to show title of a post in another post.But it shows only post id.How to solve this?
```
<?php $home_team_name = rwmb_meta( 'pb_select_home_team', 'type=select_advanced', get_the_ID() ); ?>
<?php echo esc_html( $home_team_name ); ?>
```
Thanks | Because you're outside the loop, you'll need to either know the post id of the title you want and specify it in the function parameter, or call the global $post variable if you're on the page (just not in the loop yet).
```
global $post
echo get_the_title($post->ID);
or
echo get_the_title(2);
``` |
238,693 | <p>I want to display the content of all pages on a single page, with links to each page.</p>
<p>This might sound like a daft request, but it's useful for quickly reviewing what's available on a smallish site.</p>
<p>Using the code below, I can get most of the info I want, but don't know how to add the permalink.</p>
<pre><code><?php $pages = get_pages();
foreach ($pages as $page_data) {
$content = apply_filters('the_content', $page_data->post_content);
$title = $page_data->post_title;
$slug = $page_data->post_name;
echo $title;
echo $slug;
echo $content;}
?>
</code></pre>
| [
{
"answer_id": 238698,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": -1,
"selected": false,
"text": "<p>There is probably better ways to achieve what you are wanting, but to answer your question with what you have... | 2016/09/09 | [
"https://wordpress.stackexchange.com/questions/238693",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63350/"
] | I want to display the content of all pages on a single page, with links to each page.
This might sound like a daft request, but it's useful for quickly reviewing what's available on a smallish site.
Using the code below, I can get most of the info I want, but don't know how to add the permalink.
```
<?php $pages = get_pages();
foreach ($pages as $page_data) {
$content = apply_filters('the_content', $page_data->post_content);
$title = $page_data->post_title;
$slug = $page_data->post_name;
echo $title;
echo $slug;
echo $content;}
?>
``` | Try this code to show list of page content. Page title will be the link of that page.
```
$args = array(
'post_type' => 'page', //specifying post type
'posts_per_page' => 10, //No. of Pages to show
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();?>
<h3><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><font style="color:#666666;"><?php the_title();?></a></h3>
<?php the_content(__('Continue Reading'));
endwhile;
``` |
238,697 | <p>I have a standard WordPress page category with tag_ID=92 which I want to noindex all posts in this category entirely. Is there a way to do it with actions/hooks in functions.php?</p>
| [
{
"answer_id": 238699,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": 2,
"selected": false,
"text": "<p>By noindex, I'm assuming you mean meta robots noindex, if so you could manually do this by utilizing the <a h... | 2016/09/09 | [
"https://wordpress.stackexchange.com/questions/238697",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101087/"
] | I have a standard WordPress page category with tag\_ID=92 which I want to noindex all posts in this category entirely. Is there a way to do it with actions/hooks in functions.php? | As the previous code I posted didnt work for the OP, clutching at straws, we can try to obtain the same outcome using [`get_the_category`](https://developer.wordpress.org/reference/functions/get_the_category/)
As the OP stated he was using YOAST, i'll wrap this function into the YOAST hook for robots.
```
add_filter('wpseo_robots', 'yoast_no_home_noindex', 999);
function yoast_no_home_noindex($string= "") {
$term_id = get_the_category( $post->ID );
if($term_id[0]->term_id == 92) {
$string= "noindex, nofollow";
}
return $string;
}
```
Same again, just drop this into your themes functions file. |
238,709 | <p>I've been away from Wordpress for a few months, and now I'm struggling to remember how to create a Page of Posts. It's most infuriating!</p>
<p><strong>The Current Site</strong></p>
<p>I have <code>home.php</code> set up to display the latest Posts of a Custom Post Type as the main page. It works fine. A simple <code>pre_get_posts</code> function in <code>functions.php</code> sets the CPT to be displayed:</p>
<pre><code>$query->set('post_type', 'campaign');
$query->set('posts_per_page', 11);
</code></pre>
<p>...when <code>is_home() && $query->is_main_query()</code>. <strong>This is correct, and does not need to be changed.</strong> It works great, but now the client wants a normal news blog <strong>elsewhere</strong> on the site.</p>
<p><strong>The New Version</strong></p>
<p>So... I need to add a news blog, that's not on the homepage, leaving the homepage as it is. It makes sense to me to use the default Post post type for this, and it makes sense for me to create a Page for this. But I can't seem to get a Page of Posts to work.</p>
<p>At first I created a <code>page-blog.php</code> template for a "News" Page, but it didn't pull in Posts with <code>while ( have_posts() ) : the_post();</code>. Instead it only listed <em>itself</em>...?</p>
<p>I then added a new line to my <code>pre_get_posts</code> function:</p>
<pre><code>if(is_page_template('page-news.php')) {
$query->set('post_type', 'post');
}
</code></pre>
<p>But now the page returns 404.</p>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 238712,
"author": "Harshita",
"author_id": 102498,
"author_profile": "https://wordpress.stackexchange.com/users/102498",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Changing the post type on the home page</strong></p>\n\n<p>By default, WordPress shows the post po... | 2016/09/09 | [
"https://wordpress.stackexchange.com/questions/238709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4109/"
] | I've been away from Wordpress for a few months, and now I'm struggling to remember how to create a Page of Posts. It's most infuriating!
**The Current Site**
I have `home.php` set up to display the latest Posts of a Custom Post Type as the main page. It works fine. A simple `pre_get_posts` function in `functions.php` sets the CPT to be displayed:
```
$query->set('post_type', 'campaign');
$query->set('posts_per_page', 11);
```
...when `is_home() && $query->is_main_query()`. **This is correct, and does not need to be changed.** It works great, but now the client wants a normal news blog **elsewhere** on the site.
**The New Version**
So... I need to add a news blog, that's not on the homepage, leaving the homepage as it is. It makes sense to me to use the default Post post type for this, and it makes sense for me to create a Page for this. But I can't seem to get a Page of Posts to work.
At first I created a `page-blog.php` template for a "News" Page, but it didn't pull in Posts with `while ( have_posts() ) : the_post();`. Instead it only listed *itself*...?
I then added a new line to my `pre_get_posts` function:
```
if(is_page_template('page-news.php')) {
$query->set('post_type', 'post');
}
```
But now the page returns 404.
What am I doing wrong? | Try this code in your `page-blog.php` to display list of posts
```
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'post', //Change this with your post type
'posts_per_page' => 10, //No. of Pages to show
'offset' => 0, //excluding the latest post if any
'paged' => $paged //For Pagination
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();?>
<h3><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title();?></a></h3>
<?php the_content(__('Continue Reading'));
endwhile;
wp_reset_postdata();
``` |
238,741 | <p>I have custom post type name "resources" and taxonomy called "type" with lot of terms in it. I do not want to create custom template for each term like taxonomy-type-{term}.php every time I add new term.</p>
<p>What I am trying to achieve here is a single page where it handle to check each terms. If the current term is "24622", show content and so on, but I want it dynamic so I don't want to input term ID each time a new term created. </p>
<p>The code that I use that works so far for single term is this:</p>
<pre><code><?php
$args = array (
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => 24622 //I WANT IT DYNAMIC
)
)
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
$term = $wp_query->queried_object;
while($loop->have_posts()) : $loop->the_post();
//Output what you want
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
}
?>
</code></pre>
<p>Please help. Thanks!</p>
<p><strong>UPDATE</strong></p>
<p>Here is the code that works for now but it fetches posts wrong order.</p>
<pre><code>// get all terms used by current post for specific category
$terms = get_the_terms(get_the_ID() , 'type');
// if $terms is array convert array of term objects to array of term IDs
if(is_array($terms)){
$term_ids = wp_list_pluck($terms, 'term_id');
foreach($terms as $term) {
$post_ids[] = $term->term_id;
}
// proceed with tax query
$args = array(
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => $term->term_id
)
)
);
$loop = new WP_Query($args);
if ($loop->have_posts()) {
$term = $wp_query->queried_object;
while ($loop->have_posts()):
$loop->the_post();
// Output what you want
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
}
wp_reset_postdata();
}
</code></pre>
<p><a href="https://i.stack.imgur.com/Rs8Hv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rs8Hv.jpg" alt="enter image description here"></a></p>
<p>If I click the "Case studies (2)" it supposed to show 2 posts but show 1 post. In "Advocacy maps (1)", it shows 2 posts.</p>
<p>Post 1 is related to "Case studies" and "Advocacy maps" terms<br>
Post 2 is related to "Case studies" and "Land monitoring reports"</p>
| [
{
"answer_id": 238771,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you could try the following code: </p>\n\n<pre><code>// get all terms used by current post for specific... | 2016/09/09 | [
"https://wordpress.stackexchange.com/questions/238741",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35253/"
] | I have custom post type name "resources" and taxonomy called "type" with lot of terms in it. I do not want to create custom template for each term like taxonomy-type-{term}.php every time I add new term.
What I am trying to achieve here is a single page where it handle to check each terms. If the current term is "24622", show content and so on, but I want it dynamic so I don't want to input term ID each time a new term created.
The code that I use that works so far for single term is this:
```
<?php
$args = array (
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => 24622 //I WANT IT DYNAMIC
)
)
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
$term = $wp_query->queried_object;
while($loop->have_posts()) : $loop->the_post();
//Output what you want
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
endwhile;
}
?>
```
Please help. Thanks!
**UPDATE**
Here is the code that works for now but it fetches posts wrong order.
```
// get all terms used by current post for specific category
$terms = get_the_terms(get_the_ID() , 'type');
// if $terms is array convert array of term objects to array of term IDs
if(is_array($terms)){
$term_ids = wp_list_pluck($terms, 'term_id');
foreach($terms as $term) {
$post_ids[] = $term->term_id;
}
// proceed with tax query
$args = array(
'post_type' => 'resources',
'tax_query' => array(
array(
'taxonomy' => 'type',
'field' => 'id',
'terms' => $term->term_id
)
)
);
$loop = new WP_Query($args);
if ($loop->have_posts()) {
$term = $wp_query->queried_object;
while ($loop->have_posts()):
$loop->the_post();
// Output what you want
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
endwhile;
}
wp_reset_postdata();
}
```
[](https://i.stack.imgur.com/Rs8Hv.jpg)
If I click the "Case studies (2)" it supposed to show 2 posts but show 1 post. In "Advocacy maps (1)", it shows 2 posts.
Post 1 is related to "Case studies" and "Advocacy maps" terms
Post 2 is related to "Case studies" and "Land monitoring reports" | Thank you for your time answering my unclear question. The code I found is the one that Im looking for. Thank you again :)
```
<?php
//http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters
$term_slug = get_queried_object()->slug;
if ( !$term_slug )
return;
else
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'gallery_category',
'field' => 'slug',
'terms' => $term_slug,
'posts_per_page' => 10
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="entry-content">
<?php the_excerpt(); ?>
</div><!-- .entry-content -->
<?php endwhile; // End the loop. ?>
``` |
238,749 | <p>Trying to conditionally hide the "private" prefix in front of the page title on one specific page named 'members' only.</p>
<p>I used this code in functions.php to hide the prefix on all pages.</p>
<pre><code>function title_format($content) {
return '%s';
}
add_filter('private_title_format', 'title_format');
add_filter('protected_title_format', 'title_format');
</code></pre>
<p>Tried to hook into this with the if is_page ( 'members' ) in various ways, but so far the only result i managed to get is fatal errors.</p>
| [
{
"answer_id": 238771,
"author": "Malisa",
"author_id": 71627,
"author_profile": "https://wordpress.stackexchange.com/users/71627",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you could try the following code: </p>\n\n<pre><code>// get all terms used by current post for specific... | 2016/09/09 | [
"https://wordpress.stackexchange.com/questions/238749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94259/"
] | Trying to conditionally hide the "private" prefix in front of the page title on one specific page named 'members' only.
I used this code in functions.php to hide the prefix on all pages.
```
function title_format($content) {
return '%s';
}
add_filter('private_title_format', 'title_format');
add_filter('protected_title_format', 'title_format');
```
Tried to hook into this with the if is\_page ( 'members' ) in various ways, but so far the only result i managed to get is fatal errors. | Thank you for your time answering my unclear question. The code I found is the one that Im looking for. Thank you again :)
```
<?php
//http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters
$term_slug = get_queried_object()->slug;
if ( !$term_slug )
return;
else
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'gallery_category',
'field' => 'slug',
'terms' => $term_slug,
'posts_per_page' => 10
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="entry-content">
<?php the_excerpt(); ?>
</div><!-- .entry-content -->
<?php endwhile; // End the loop. ?>
``` |
238,807 | <p>I have used a theme that includes the word "courses" throughout the theme by default as it is an online education platform. I am however creating a website with a similar design, but for projects so i would like to replace the word "courses" throughout the theme with the word "projects"
I have minimum experience with coding and even html so please dumb it down for me :)
Thank You in advance</p>
| [
{
"answer_id": 238810,
"author": "Zeeshan",
"author_id": 102553,
"author_profile": "https://wordpress.stackexchange.com/users/102553",
"pm_score": -1,
"selected": false,
"text": "<p>The simplest thing you can do is export the database and find/replace <code>courses</code> with <code>proj... | 2016/09/10 | [
"https://wordpress.stackexchange.com/questions/238807",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102552/"
] | I have used a theme that includes the word "courses" throughout the theme by default as it is an online education platform. I am however creating a website with a similar design, but for projects so i would like to replace the word "courses" throughout the theme with the word "projects"
I have minimum experience with coding and even html so please dumb it down for me :)
Thank You in advance | I see some great answers for how to do a search and replace on a given string found in the database. However as I understand the OP's question, they are looking to replace text found in the theme files, as the question says "I have used a theme that includes the word "courses" throughout the theme by default...".
If this was a case where the theme anticipated this need, or was already changing the text of a plugin, like some themes change the WooCommerce cart text from "add to cart" to "purchase course". Then there would be filter hooks available but you would need well written documentation, or the ability to look through the code to determine this. (<https://developer.wordpress.org/reference/functions/add_filter/>)
A fast simple clever way would be to add this to a child theme's `functions.php` file. (<https://codex.wordpress.org/Child_Themes>)
```
function start_modify_html() {
ob_start();
}
function end_modify_html() {
$html = ob_get_clean();
$html = str_replace( 'Course', 'Project', $html );
$html = str_replace( 'course', 'project', $html );
echo $html;
}
add_action( 'wp_head', 'start_modify_html' );
add_action( 'wp_footer', 'end_modify_html' );
```
The last way would be to edit the theme files, if the theme were ever updated all of your changes would be lost. To do this you could download the theme and use any decent text editor to do a search and replace, then upload. I do this with Atom editor all the time and it is open source and free to download. (<http://flight-manual.atom.io/using-atom/sections/find-and-replace/>) |
238,850 | <p>I don't know why <code>get_term()</code> works on other pages but won't work in <code>functions.php</code>. Using <code>get_term()</code> in <code>functions.php</code> causes WordPress to report the error <em>Invalid taxonomy</em>.</p>
<p>my <code>function.php</code> which is ajax handler and already registered for ajax</p>
<pre><code> public function load_destination()
{
global $wpdb;
$termId = $_POST['termid'];
$term = get_term($termid,'package_state');
$args = array(
'post_type' => 'package',
'tax_query' => array(
array(
'taxonomy' => 'package_state',
'field' => 'id',
'terms' => $termId
)
)
);
$query = new WP_Query( $args );
$collection=[];
$count =1;
while($query->have_posts()) : $query->the_post();
$collection['data'][] = // i need to set term data here $term;
$count++;
endwhile;
wp_send_json($collection);
}
</code></pre>
| [
{
"answer_id": 238851,
"author": "bbruman",
"author_id": 102212,
"author_profile": "https://wordpress.stackexchange.com/users/102212",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/Function_Reference/get_term\" rel=\"nofollow\">https://codex.wordpres... | 2016/09/11 | [
"https://wordpress.stackexchange.com/questions/238850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66294/"
] | I don't know why `get_term()` works on other pages but won't work in `functions.php`. Using `get_term()` in `functions.php` causes WordPress to report the error *Invalid taxonomy*.
my `function.php` which is ajax handler and already registered for ajax
```
public function load_destination()
{
global $wpdb;
$termId = $_POST['termid'];
$term = get_term($termid,'package_state');
$args = array(
'post_type' => 'package',
'tax_query' => array(
array(
'taxonomy' => 'package_state',
'field' => 'id',
'terms' => $termId
)
)
);
$query = new WP_Query( $args );
$collection=[];
$count =1;
while($query->have_posts()) : $query->the_post();
$collection['data'][] = // i need to set term data here $term;
$count++;
endwhile;
wp_send_json($collection);
}
``` | It sounds like you are are using `get_term()` for a custom taxonomy. If you're using `get_term()` inside `functions.php` and outside of a hooked function, that code is going to be run immediately when `functions.php` is loaded. Your custom taxonomy will not have been registered at this point, because that happens on the `init` hook.
Your code is working inside of your page template because WordPress has loaded the custom taxonomies at that point.
If you were to try something like `$term = get_term( '2', 'category' );` (where `2` is a valid term ID) in `functions.php`, it would actually work, because WordPress loads built-in taxonomies in `wp-settings.php` (which is very early in the loading process) for backwards compatibility reasons. WordPress also registers default taxonomies on `init`, by the way. This is explained in the documentation block for `create_initial_taxonomies()` in [`/wp-includes/taxonomy.php`](https://github.com/WordPress/WordPress/blob/master/wp-includes/taxonomy.php#L13).
Anyway, running `get_term()` outside of a hooked function in `functions.php` is not the right way to do it, and more code would be needed to help you further. |
238,863 | <p>I am beginner of wordpress. </p>
<pre><code> <?php if( have_posts() ):
while( have_posts() ): the_post(); ?>
<p><?php the_title(); ?></p>
<p><?php the_category(); ?></p>
<p><?php the_content(); ?></p>
<?php
endwhile;
endif;
?>
</code></pre>
<p>I use this post loop once, But now this doesn't work. Where am I doing mistake. I search but I can't understand very well. Thank you.</p>
<p>----------------------------- EDİT -----------------------------</p>
<p>I create topic like that.</p>
<p><a href="https://i.stack.imgur.com/v9WCv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v9WCv.png" alt="enter image description here"></a></p>
<p>And result is like this: (just lile page title).</p>
<p><a href="https://i.stack.imgur.com/MCgor.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MCgor.png" alt="enter image description here"></a></p>
<p>Also if you want my page.php code :</p>
<pre><code> <?php if(is_page(albumlerimiz)): ?>
<div id="albumlerimiz">
<div class="baslik">
<h1> Albümlerimiz </h1>
</div>
<div class="content">
<div class="container">
<div class="center-align">
<div class="portfolio_filter">
<ul>
<li data-filter="*"> TÜM ALBÜMLER </li>
<li data-filter=".dugun"> DÜGÜN ALBÜMLERİ </li>
<li data-filter=".cocuk"> ÇOCUK ALBÜMLERİ </li>
<li data-filter=".okul"> OKUL ALBÜMLERİ </li>
<li data-filter=".sunnet"> SÜNNET ALBÜMLERİ </li>
</ul>
</div>
<div class="portfolio_items">
<?php if( have_posts() ):
while( have_posts() ): the_post(); ?>
<p><?php the_title(); ?></p>
<p><?php the_category(); ?></p>
<p><?php the_content(); ?></p>
<?php
endwhile;
endif;
?>
</div>
</div>
</div>
</div>
<?php endif ?>
</code></pre>
| [
{
"answer_id": 238879,
"author": "Sami",
"author_id": 102593,
"author_profile": "https://wordpress.stackexchange.com/users/102593",
"pm_score": 2,
"selected": true,
"text": "<p>Go to admin (Wordpress Portal) > Settings > Reading, look to \"Front page displays\" and make sure \"Your lates... | 2016/09/11 | [
"https://wordpress.stackexchange.com/questions/238863",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96869/"
] | I am beginner of wordpress.
```
<?php if( have_posts() ):
while( have_posts() ): the_post(); ?>
<p><?php the_title(); ?></p>
<p><?php the_category(); ?></p>
<p><?php the_content(); ?></p>
<?php
endwhile;
endif;
?>
```
I use this post loop once, But now this doesn't work. Where am I doing mistake. I search but I can't understand very well. Thank you.
----------------------------- EDİT -----------------------------
I create topic like that.
[](https://i.stack.imgur.com/v9WCv.png)
And result is like this: (just lile page title).
[](https://i.stack.imgur.com/MCgor.png)
Also if you want my page.php code :
```
<?php if(is_page(albumlerimiz)): ?>
<div id="albumlerimiz">
<div class="baslik">
<h1> Albümlerimiz </h1>
</div>
<div class="content">
<div class="container">
<div class="center-align">
<div class="portfolio_filter">
<ul>
<li data-filter="*"> TÜM ALBÜMLER </li>
<li data-filter=".dugun"> DÜGÜN ALBÜMLERİ </li>
<li data-filter=".cocuk"> ÇOCUK ALBÜMLERİ </li>
<li data-filter=".okul"> OKUL ALBÜMLERİ </li>
<li data-filter=".sunnet"> SÜNNET ALBÜMLERİ </li>
</ul>
</div>
<div class="portfolio_items">
<?php if( have_posts() ):
while( have_posts() ): the_post(); ?>
<p><?php the_title(); ?></p>
<p><?php the_category(); ?></p>
<p><?php the_content(); ?></p>
<?php
endwhile;
endif;
?>
</div>
</div>
</div>
</div>
<?php endif ?>
``` | Go to admin (Wordpress Portal) > Settings > Reading, look to "Front page displays" and make sure "Your latest posts" is checked
<https://codex.wordpress.org/Settings_Reading_Screen> |
238,882 | <p>I'm not experienced with the WordPress. My goal is to display all the posts on the page.</p>
<p>I was trying to display posts on a page like so:</p>
<pre><code><?php if (have_posts()) : while (have_posts()) : the_post(); ?>
...
<?php endwhile; else: ?>
<p><?php _e( 'Sorry, no pages found.' ); ?></p>
<?php endif; ?>
</code></pre>
<p>I've faced a problem that there is a limit of 5 posts to be displayed by default. I tried to use custom <code>WP_Query</code>:</p>
<pre><code><?php
$all_query = new WP_Query(array(
'post_type'=>'post',
'post_status'=>'publish',
'posts_per_page'=>-1,
));
if ($all_query->have_posts()) : while ($all_query->have_posts()) : $all_query->the_post();
?>
</code></pre>
<p>It shows all the posts, but it also shows all the posts even on category archive pages (i.e. posts from another category).</p>
<p>As I understand, I can create <code>archive.php</code> page for categories and authors.</p>
<p>Is there any solution to use loop to show all the posts only of the current category or author?</p>
| [
{
"answer_id": 238893,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The number of posts displayed in any loop by default is controlled by <em>Settings > Blog pages show at mos... | 2016/09/11 | [
"https://wordpress.stackexchange.com/questions/238882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82592/"
] | I'm not experienced with the WordPress. My goal is to display all the posts on the page.
I was trying to display posts on a page like so:
```
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
...
<?php endwhile; else: ?>
<p><?php _e( 'Sorry, no pages found.' ); ?></p>
<?php endif; ?>
```
I've faced a problem that there is a limit of 5 posts to be displayed by default. I tried to use custom `WP_Query`:
```
<?php
$all_query = new WP_Query(array(
'post_type'=>'post',
'post_status'=>'publish',
'posts_per_page'=>-1,
));
if ($all_query->have_posts()) : while ($all_query->have_posts()) : $all_query->the_post();
?>
```
It shows all the posts, but it also shows all the posts even on category archive pages (i.e. posts from another category).
As I understand, I can create `archive.php` page for categories and authors.
Is there any solution to use loop to show all the posts only of the current category or author? | The number of posts displayed in any loop by default is controlled by *Settings > Blog pages show at most*. To show all posts, you can enter a huge number, but `-1` (which is the value to use for the `posts_per_page` paramerter in `WP_Query`) does not work here.
It is possible to show all posts on the category and author archives while still showing a limited number of posts within your main blog area. To do this, use the *Blog pages to show at most* setting to configure the number of posts to show within the main blog, then use the `pre_get_posts` hook to modify the other archives to suit your preferences. Add the following code to your theme's `functions.php` file:
```
/**
* Modify the query to show all posts on category and author archives.
*
*/
function wpse238882_pre_get_posts( $query ) {
if ( ( $query->is_author() || $query->is_category() ) && $query->is_main_query() ) {
$query->set( 'posts_per_page', -1 );
}
}
add_action( 'pre_get_posts', 'wpse238882_pre_get_posts' );
```
You can still use the `author.php` and `category.php` templates to customize the output of your author and category archives, but this is not necessary to simply modify the number of posts displayed, which has been demonstrated above. Check out the [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) Codex entry for more information on customizing templates. |
238,889 | <p>I'm trying to make a social links menu for the footer in my theme. I want a menu to be customisable in Dashboard, I want the links to be relative to what's put in there.</p>
<p>Originally to get that, I did this: </p>
<pre><code><a href="http://www.facebook.com/" target="_blank"><i class="fa fa-facebook circle"></i></a>
<a href="http://www.google.com/" target="_blank"><i class="fa fa-google-plus circle"></i></a>
<a href="http://www.twitter.com/" target="_blank"><i class="fa fa-twitter circle"></i></a>
<a href="http://www.linkedin.com/" target="_blank"><i class="fa fa-linkedin circle"></i></a>
</code></pre>
<p>For hard-coded menu items.</p>
<p>Now, I want to use</p>
<pre><code><?php wp_nav_menu( array( 'theme_location' => 'social' ) ); ?>
</code></pre>
<p>To generate the <code><li></code> but realise that doing so puts the link label, i.e. <code>Facebook</code> inside the <code><li><a></code> tags.</p>
<p>i.e. <code><li class="fa fa-facebook circle"><a href="fb.com">Facebook</a></li></code></p>
<p>Which isn't that great because 1. Facebook label gets in the way and 2. is the only thing that is clickable.</p>
<p>I want to get the link tag on the outside of my classes (being set automatically by Wordpress too through Menu customisation)</p>
<p>I realise I could write the <code><i></code> class inside the label for each menu item, but that defeats the purpose I'm going after here.</p>
<p>Edit: I'd love a solution that doesn't exclude hacking in some way.</p>
| [
{
"answer_id": 238902,
"author": "C C",
"author_id": 83299,
"author_profile": "https://wordpress.stackexchange.com/users/83299",
"pm_score": 2,
"selected": true,
"text": "<p>This is a tough one. Normally I'd say use <code>text-indent:-99999px;</code> as part of the markup for <code><... | 2016/09/11 | [
"https://wordpress.stackexchange.com/questions/238889",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102600/"
] | I'm trying to make a social links menu for the footer in my theme. I want a menu to be customisable in Dashboard, I want the links to be relative to what's put in there.
Originally to get that, I did this:
```
<a href="http://www.facebook.com/" target="_blank"><i class="fa fa-facebook circle"></i></a>
<a href="http://www.google.com/" target="_blank"><i class="fa fa-google-plus circle"></i></a>
<a href="http://www.twitter.com/" target="_blank"><i class="fa fa-twitter circle"></i></a>
<a href="http://www.linkedin.com/" target="_blank"><i class="fa fa-linkedin circle"></i></a>
```
For hard-coded menu items.
Now, I want to use
```
<?php wp_nav_menu( array( 'theme_location' => 'social' ) ); ?>
```
To generate the `<li>` but realise that doing so puts the link label, i.e. `Facebook` inside the `<li><a>` tags.
i.e. `<li class="fa fa-facebook circle"><a href="fb.com">Facebook</a></li>`
Which isn't that great because 1. Facebook label gets in the way and 2. is the only thing that is clickable.
I want to get the link tag on the outside of my classes (being set automatically by Wordpress too through Menu customisation)
I realise I could write the `<i>` class inside the label for each menu item, but that defeats the purpose I'm going after here.
Edit: I'd love a solution that doesn't exclude hacking in some way. | This is a tough one. Normally I'd say use `text-indent:-99999px;` as part of the markup for `<a>` -- to get that link text off the screen. But you have that `fa` italic tag which is really text as well - so it gets shifted off the screen, too.
This solution is pretty ugly but you can probably tweak it for your use.
Wrap the social links inside a div:
```
<div id="social-wrapper">
<a href="http://www.facebook.com/" target="_blank"><i class="fa fa-facebook circle"></i>Facebook</a>
<a href="http://www.google.com/" target="_blank"><i class="fa fa-google-plus circle"></i>Google</a>
<a href="http://www.twitter.com/" target="_blank"><i class="fa fa-twitter circle"></i>Twitter</a>
<a href="http://www.linkedin.com/" target="_blank"><i class="fa fa-linkedin circle"></i>LinkedIn</a>
</div>
```
Then, .css like this:
```
#social-wrapper .fa {
color: #000;
}
#social-wrapper a {
color: transparent;
display: inline-block;
margin: 0 8px;
overflow: hidden;
width: 15px;
}
```
Set that width to accommodate your .fa icon width. Here is a [jsfiddle](https://jsfiddle.net/t1zk4u5n/) that shows how it works.
**EDIT:**
ok, didn't realize you couldn't get the above solution to work. Here's a less ugly version, still just using CSS. Anything beyond this and you will need to write your own implementation of `wp_nav_menu` to get the content the way you want it and not rely on a css solution.
Same HTML as above, with a wrapper div.
This CSS:
```
#social-wrapper {
text-indent: -99999px;
}
#social-wrapper a {
width: 30px;
float: left;
}
#social-wrapper .fa {
display: inline-block;
vertical-align: middle;
width: 0;
text-indent: 99999px;
}
```
And here's [another fiddle](https://jsfiddle.net/r21fooqh/) showing how it works. |
238,905 | <p>I need to add revision support to WooCommerce Products (at least for the main content). The developers are unwilling to do this until there is some support on Wordpress for the extra product fields: <a href="https://github.com/woothemes/woocommerce/issues/2178" rel="nofollow">https://github.com/woothemes/woocommerce/issues/2178</a></p>
<p>As I prefer partial revision support than nothing, I took a look around and found the following.</p>
<p>As of WooCommerce 2.6.4, we have this on woocommerce/includes/class-wc-post-types.php:</p>
<pre><code> register_post_type( 'product',
apply_filters( 'woocommerce_register_post_type_product',
array(
'labels' => array(
'name' => __( 'Products', 'woocommerce' ),
'singular_name' => __( 'Product', 'woocommerce' ),
'menu_name' => _x( 'Products', 'Admin menu name', 'woocommerce' ),
'add_new' => __( 'Add Product', 'woocommerce' ),
'add_new_item' => __( 'Add New Product', 'woocommerce' ),
'edit' => __( 'Edit', 'woocommerce' ),
'edit_item' => __( 'Edit Product', 'woocommerce' ),
'new_item' => __( 'New Product', 'woocommerce' ),
'view' => __( 'View Product', 'woocommerce' ),
'view_item' => __( 'View Product', 'woocommerce' ),
'search_items' => __( 'Search Products', 'woocommerce' ),
'not_found' => __( 'No Products found', 'woocommerce' ),
'not_found_in_trash' => __( 'No Products found in trash', 'woocommerce' ),
'parent' => __( 'Parent Product', 'woocommerce' ),
'featured_image' => __( 'Product Image', 'woocommerce' ),
'set_featured_image' => __( 'Set product image', 'woocommerce' ),
'remove_featured_image' => __( 'Remove product image', 'woocommerce' ),
'use_featured_image' => __( 'Use as product image', 'woocommerce' ),
'insert_into_item' => __( 'Insert into product', 'woocommerce' ),
'uploaded_to_this_item' => __( 'Uploaded to this product', 'woocommerce' ),
'filter_items_list' => __( 'Filter products', 'woocommerce' ),
'items_list_navigation' => __( 'Products navigation', 'woocommerce' ),
'items_list' => __( 'Products list', 'woocommerce' ),
),
'description' => __( 'This is where you can add new products to your store.', 'woocommerce' ),
'public' => true,
'show_ui' => true,
'capability_type' => 'product',
'map_meta_cap' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'hierarchical' => false, // Hierarchical causes memory issues - WP loads all records!
'rewrite' => $product_permalink ? array( 'slug' => untrailingslashit( $product_permalink ), 'with_front' => false, 'feeds' => true ) : false,
'query_var' => true,
'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'comments', 'custom-fields', 'page-attributes', 'publicize', 'wpcom-markdown' ),
'has_archive' => ( $shop_page_id = wc_get_page_id( 'shop' ) ) && get_post( $shop_page_id ) ? get_page_uri( $shop_page_id ) : 'shop',
'show_in_nav_menus' => true
)
)
);
</code></pre>
<p>I can make it work adding a <code>'revisions'</code> to <code>'supports'</code> array.</p>
<p>But every upgrade will revert this change.</p>
<p>Now the question is: how to make this change as a child theme/plugin/whatever that can keep working even after WooCommerce upgrades?</p>
| [
{
"answer_id": 238906,
"author": "Roy Ho",
"author_id": 67572,
"author_profile": "https://wordpress.stackexchange.com/users/67572",
"pm_score": 5,
"selected": true,
"text": "<p>As you pointed out already there is a filter.</p>\n\n<pre><code>add_filter( 'woocommerce_register_post_type_pro... | 2016/09/11 | [
"https://wordpress.stackexchange.com/questions/238905",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102609/"
] | I need to add revision support to WooCommerce Products (at least for the main content). The developers are unwilling to do this until there is some support on Wordpress for the extra product fields: <https://github.com/woothemes/woocommerce/issues/2178>
As I prefer partial revision support than nothing, I took a look around and found the following.
As of WooCommerce 2.6.4, we have this on woocommerce/includes/class-wc-post-types.php:
```
register_post_type( 'product',
apply_filters( 'woocommerce_register_post_type_product',
array(
'labels' => array(
'name' => __( 'Products', 'woocommerce' ),
'singular_name' => __( 'Product', 'woocommerce' ),
'menu_name' => _x( 'Products', 'Admin menu name', 'woocommerce' ),
'add_new' => __( 'Add Product', 'woocommerce' ),
'add_new_item' => __( 'Add New Product', 'woocommerce' ),
'edit' => __( 'Edit', 'woocommerce' ),
'edit_item' => __( 'Edit Product', 'woocommerce' ),
'new_item' => __( 'New Product', 'woocommerce' ),
'view' => __( 'View Product', 'woocommerce' ),
'view_item' => __( 'View Product', 'woocommerce' ),
'search_items' => __( 'Search Products', 'woocommerce' ),
'not_found' => __( 'No Products found', 'woocommerce' ),
'not_found_in_trash' => __( 'No Products found in trash', 'woocommerce' ),
'parent' => __( 'Parent Product', 'woocommerce' ),
'featured_image' => __( 'Product Image', 'woocommerce' ),
'set_featured_image' => __( 'Set product image', 'woocommerce' ),
'remove_featured_image' => __( 'Remove product image', 'woocommerce' ),
'use_featured_image' => __( 'Use as product image', 'woocommerce' ),
'insert_into_item' => __( 'Insert into product', 'woocommerce' ),
'uploaded_to_this_item' => __( 'Uploaded to this product', 'woocommerce' ),
'filter_items_list' => __( 'Filter products', 'woocommerce' ),
'items_list_navigation' => __( 'Products navigation', 'woocommerce' ),
'items_list' => __( 'Products list', 'woocommerce' ),
),
'description' => __( 'This is where you can add new products to your store.', 'woocommerce' ),
'public' => true,
'show_ui' => true,
'capability_type' => 'product',
'map_meta_cap' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'hierarchical' => false, // Hierarchical causes memory issues - WP loads all records!
'rewrite' => $product_permalink ? array( 'slug' => untrailingslashit( $product_permalink ), 'with_front' => false, 'feeds' => true ) : false,
'query_var' => true,
'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'comments', 'custom-fields', 'page-attributes', 'publicize', 'wpcom-markdown' ),
'has_archive' => ( $shop_page_id = wc_get_page_id( 'shop' ) ) && get_post( $shop_page_id ) ? get_page_uri( $shop_page_id ) : 'shop',
'show_in_nav_menus' => true
)
)
);
```
I can make it work adding a `'revisions'` to `'supports'` array.
But every upgrade will revert this change.
Now the question is: how to make this change as a child theme/plugin/whatever that can keep working even after WooCommerce upgrades? | As you pointed out already there is a filter.
```
add_filter( 'woocommerce_register_post_type_product', 'wpse_modify_product_post_type' );
function wpse_modify_product_post_type( $args ) {
$args['supports'][] = 'revisions';
return $args;
}
```
Put that in your child theme's functions.php file. |
238,911 | <p>I have this code I want to implement onto my website. I have successfully set up a child theme. This code is suppose to change the background every day of the week. I am not all too familiar with Wordpress, and I am wondering where I should place it and how. Can someone please give me step by step instruction what I need to do?</p>
<p>The code is below. Thank you very much.</p>
<hr>
<pre><code>function chgDailyImg()
{
var imagearray = new Array();
imagearray[0] = "sundaypic.jpg";
imagearray[1] = "mondaypic.jpg";
imagearray[2] = "tuesdaypic.jpg";
imagearray[3] = "wednesdaypic.jpg";
imagearray[4] = "thursdaypic.jpg";
imagearray[5] = "fridaypic.jpg";
imagearray[6] = "saturdaypic.jpg";
var d = new Date(); /*** create a date object for use ***/
var i = d.getDay(); /*** use the date object to get the day of the week - this will be a number from 0 to 6 - sunday=0, saturday=6 -it's the way counting works in javascript it starts at 0 like in the arrays ***/
document.getElementById("dailyImg").src = imagearray;
}/* CSS Document *//* CSS Document */
</code></pre>
| [
{
"answer_id": 238916,
"author": "Dave Romsey",
"author_id": 2807,
"author_profile": "https://wordpress.stackexchange.com/users/2807",
"pm_score": 1,
"selected": false,
"text": "<p>The code you've posted is JavaScript, and it should be placed within a JavaScript file inside of your child... | 2016/09/12 | [
"https://wordpress.stackexchange.com/questions/238911",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102602/"
] | I have this code I want to implement onto my website. I have successfully set up a child theme. This code is suppose to change the background every day of the week. I am not all too familiar with Wordpress, and I am wondering where I should place it and how. Can someone please give me step by step instruction what I need to do?
The code is below. Thank you very much.
---
```
function chgDailyImg()
{
var imagearray = new Array();
imagearray[0] = "sundaypic.jpg";
imagearray[1] = "mondaypic.jpg";
imagearray[2] = "tuesdaypic.jpg";
imagearray[3] = "wednesdaypic.jpg";
imagearray[4] = "thursdaypic.jpg";
imagearray[5] = "fridaypic.jpg";
imagearray[6] = "saturdaypic.jpg";
var d = new Date(); /*** create a date object for use ***/
var i = d.getDay(); /*** use the date object to get the day of the week - this will be a number from 0 to 6 - sunday=0, saturday=6 -it's the way counting works in javascript it starts at 0 like in the arrays ***/
document.getElementById("dailyImg").src = imagearray;
}/* CSS Document *//* CSS Document */
``` | In this scenario, the tag that you want to call to execute your function is the [`wp_head()`](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head).
Looking at the code you provides, you have the idea down, but I decided to rewrite it differently. In your child theme's [`functions.php`](https://codex.wordpress.org/Child_Themes#Using_functions.php) file, add the following:
```
add_action( 'wp_head', 'wpse_238911_weekly_background' );
function wpse_238911_weekly_background() {
$day = date( "l" );
switch( $day ) {
case 'Monday':
$background_image = 'mon-img.jpg';
break;
case 'Tuesday':
$background_image = 'tue-img.jpg';
break;
case 'Wednesday':
$background_image = 'wed-img.jpg';
break;
case 'Thursday':
$background_image = 'thu-img.jpg';
break;
case 'Friday':
$background_image = 'fri-img.jpg';
break;
case 'Saturday':
$background_image = 'sat-img.jpg';
break;
case 'Sunday':
default:
$background_image = 'sun-img.jpg';
break;
}
?>
<style type="text/css">
body {
background-image: url( 'http://web.site/img/<?php echo $background_image; ?>' );
}
</style>
<?php
}
```
Just switch out the `mon-img.jpg` to your actual image names and change the `http://web.site/img/` path to wherever you will be having your day-of-the-week images stored. |
238,915 | <p>How can a <strong>category</strong> be assigned to a <em>new front-end post</em> submission?<br><br>
<em>Posting works</em>, Category is not assigned.
Would like to be able to add more than one, if possible.<br>
Both are CPT and custom taxonomies.<br><br></p>
<pre><code>if ( isset( $_POST['submitted'] ) && isset( $_POST['new_post_nonce_field'] ) && wp_verify_nonce( $_POST['new_post_nonce_field'], 'new_post_nonce_action' ) ) {
$new_post = array(
'post_content' => $_POST['post-content'],
'post_title' => wp_strip_all_tags( $_POST['post-title'] ),
'post_type' => 'custom_pt',
'post_category' => array(
'custom_tax' => $_POST['custom_tax']
),
);
if ( !$hasError == true ) {
$post_id = wp_insert_post( $new_post );
if ( post_id ) {
wp_redirect( home_url() );
}
}
}
</code></pre>
<p>.</p>
<pre><code> <form id="new_post" method="POST" action="" enctype="multipart/form-data">
<label for="post-title">The Title</label>
<input id="post-title" name="post-title" type="text" />
<label for="post-content">The Content</label>
<textarea id="post-content" name="post-content"></textarea>
<label for="custom_tax">The Categories</label>
<?php wp_dropdown_categories( 'tab_index=10&taxonomy=custom_tax&name=custom_tax&class=custom_tax&show_option_all=Select a category' ); ?>
<?php wp_nonce_field( 'new_post_nonce_action', 'new_post_nonce_field' ); ?>
<button type="submit">Publish</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
</code></pre>
<p>Thank You.</p>
| [
{
"answer_id": 238923,
"author": "Navin Bhudiya",
"author_id": 98536,
"author_profile": "https://wordpress.stackexchange.com/users/98536",
"pm_score": -1,
"selected": false,
"text": "<p>By using <strong>wp_set_object_terms</strong> you can set post category , for more details please foll... | 2016/09/12 | [
"https://wordpress.stackexchange.com/questions/238915",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101510/"
] | How can a **category** be assigned to a *new front-end post* submission?
*Posting works*, Category is not assigned.
Would like to be able to add more than one, if possible.
Both are CPT and custom taxonomies.
```
if ( isset( $_POST['submitted'] ) && isset( $_POST['new_post_nonce_field'] ) && wp_verify_nonce( $_POST['new_post_nonce_field'], 'new_post_nonce_action' ) ) {
$new_post = array(
'post_content' => $_POST['post-content'],
'post_title' => wp_strip_all_tags( $_POST['post-title'] ),
'post_type' => 'custom_pt',
'post_category' => array(
'custom_tax' => $_POST['custom_tax']
),
);
if ( !$hasError == true ) {
$post_id = wp_insert_post( $new_post );
if ( post_id ) {
wp_redirect( home_url() );
}
}
}
```
.
```
<form id="new_post" method="POST" action="" enctype="multipart/form-data">
<label for="post-title">The Title</label>
<input id="post-title" name="post-title" type="text" />
<label for="post-content">The Content</label>
<textarea id="post-content" name="post-content"></textarea>
<label for="custom_tax">The Categories</label>
<?php wp_dropdown_categories( 'tab_index=10&taxonomy=custom_tax&name=custom_tax&class=custom_tax&show_option_all=Select a category' ); ?>
<?php wp_nonce_field( 'new_post_nonce_action', 'new_post_nonce_field' ); ?>
<button type="submit">Publish</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
```
Thank You. | I checked and it works with this:
```
$new_post = array(
'post_content' => $_POST['post-content'],
'post_title' => wp_strip_all_tags( $_POST['post-title'] ),
'post_type' => 'custom_pt'
);
```
*note: I used a text input for the single category*
```
<input id="input-name-value" name="input-name-value" type="text" />
```
I havent tried it with a select - option dropdown. or more than 1 category.
```
$post_id = wp_insert_post( $new_post );
wp_set_object_terms( $post_id, $_POST['input-name-value'], 'yourCategory' );
```
It would be nice if someone could pimp this out in order to get full functionallity.
Thanks. |
238,941 | <p>I'm trying to add some javascript to my theme customizer. My JS file is loaded no problem and my document ready event works but <code>wp.customize.bind()</code> isn't calling my callback.</p>
<pre><code>jQuery(document).on('ready', function(){
console.log('binding')
wp.customize.bind('ready', function(){
console.log('ready')
})
})
</code></pre>
<p><code>binding</code> gets outputed to the console but <code>ready</code> does not.</p>
<p>What am I missing? there seems to be little to no documentation on using the javascript here.</p>
| [
{
"answer_id": 284297,
"author": "Digvijayad",
"author_id": 118765,
"author_profile": "https://wordpress.stackexchange.com/users/118765",
"pm_score": 0,
"selected": false,
"text": "<p>I had same problem. \nThe reason it was not binding for me was because I had this error <code>\"Uncaught... | 2016/09/12 | [
"https://wordpress.stackexchange.com/questions/238941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85357/"
] | I'm trying to add some javascript to my theme customizer. My JS file is loaded no problem and my document ready event works but `wp.customize.bind()` isn't calling my callback.
```
jQuery(document).on('ready', function(){
console.log('binding')
wp.customize.bind('ready', function(){
console.log('ready')
})
})
```
`binding` gets outputed to the console but `ready` does not.
What am I missing? there seems to be little to no documentation on using the javascript here. | Do not put the Customizer `ready` event handler inside of the jQuery `event` handler. The Customizer `ready` will trigger at jQuery `ready`, so you are adding the event handler too late. Just do:
```
wp.customize.bind('ready', function(){
console.log('ready');
});
```
Your JS needs to be enqueued with `customize-controls` script as its dependency. Enqueue at the `customize_controls_enqueue_scripts` action. |